那么为什么这不起作用?我正在创建一个匹配公式的正则表达式(然后是更大的标准描述的一部分)。但我被困在这里,因为它似乎不想匹配公式中的嵌入公式。
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})\%?/
关于 ruby 递归正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2648054/