正则表达式的o修饰符是什么意思?
Ruby regexp有一些选项(例如i
, x
, m
, o
)。 例如, i
意思是忽略大小写。
o
选项意味着什么? 在ri Regexp
,它表示o
表示只执行#{}
插值一次。 但是当我这样做时:
a = 'one' b = /#{a}/ a = 'two'
b
不会改变(它保持/one/
)。 我错过了什么?
直接来自正则表达式的首选源 :
/o
导致特定正则表达式文字中的任何#{...}
替换仅在第一次计算时执行一次。 否则,每次文字生成Regexp对象时都会执行替换。
我也可以打开这个用法示例 :
# avoid interpolating patterns like this if the pattern # isn't going to change: pattern = ARGV.shift ARGF.each do |line| print line if line =~ /#{pattern}/ end # the above creates a new regex each iteration. Instead, # use the /o modifier so the regex is compiled only once pattern = ARGV.shift ARGF.each do |line| print line if line =~ /#{pattern}/o end
所以我想对于编译器而言,这是一个多次执行的单行 。