微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby递归正则表达式

那为什么这不起作用?我正在创建一个匹配公式的正则表达式(这是更大的标准描述的一部分).但是我被困在这里,因为它似乎不想匹配公式中的嵌入式公式.
stat        = /(Stat3|Stat2|Stat1)/

number_sym  = /[0-9]*/
formula_sym = /((target's )?#{stat}|#{number_sym}|N#{number_sym})\%?/
math_sym    = /(\+|\-|\*|\/|\%)/

formula     = /^\((#{formula}|#{formula_sym})( #{math_sym} (#{formula}|#{formula_sym}))?\)$/

p "(target's Stat2 * N1%)".match(formula).to_s #matches
p "((target's Stat2 * N1%) + 3)".match(formula).to_s #no match
p "(Stat1 + ((target's Stat2 * N1%) + 3))".match(formula).to_s #no match

解决方法

当您使用#{}语法时,Ruby使用to_s将Regexp对象转换为字符串.看看将Regexp对象转换为字符串时会发生什么:
irb> re = /blah/
  => /blah/
irb> re.to_s
  => "(?-mix:blah)"
irb> "my regex: #{re}"
  => "my regex: (?-mix:blah)"
irb> /my regex: #{re}/
  => /my regex: (?-mix:blah)/

获取所需的字符串(在我的示例中,“blah”),请使用Regexp#source方法

irb> re.source
"blah"

所以要使用你的例子:

formula_sym = /((target's )?#{stat.source}|#{number_sym.source}|N#{number_sym.source})\%?/

原文地址:https://www.jb51.cc/ruby/264771.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐