Ruby 正则表达式有一些选项(例如 i
、x
、m
、o
)。例如,i
表示忽略大小写。
o
选项是什么意思?在 ri Regexp
中,它说 o
表示只执行一次 #{}
插值。但是当我这样做时:
a = 'one'
b = /#{a}/
a = 'two'
b
不变(它保持为 /one/
)。我错过了什么?
最佳答案
直接来自 the go-to source for regular expressions :
/o
causes any#{...}
substitutions in a particular regex literal to be performed just once, the first time it is evaluated. Otherwise, the substitutions will be performed every time the literal generates a Regexp object.
我也可以找到 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
所以我想这对编译器来说更像是一件事情,因为单行会被多次执行。
关于ruby - 正则表达式的 o 修饰符是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13334807/