Ruby regexp有一些选项(例如i
,x
,m
,o
)。例如,i
表示忽略大小写。
o
选项是什么意思?在ri Regexp
中,它表示o
表示仅执行一次#{}
插值。但是当我这样做时:
a = 'one'
b = /#{a}/
a = 'two'
b
不会更改(保持/one/
)。我错过了什么?
答案 0 :(得分:19)
直接来自the go-to source for regular expressions:
/o
导致特定正则表达式文字中的任何#{...}
替换仅在第一次计算时执行一次。否则,每次文字生成Regexp对象时都会执行替换。
我也可以出现this usage example:
# 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
所以我想这对于编译器而言是一件事,对于多次执行的单行。