正则表达式的o修饰符是什么意思?

时间:2012-11-11 19:52:20

标签: ruby regex

Ruby regexp有一些选项(例如ixmo)。例如,i表示忽略大小写。

o选项是什么意思?在ri Regexp中,它表示o表示仅执行一次#{}插值。但是当我这样做时:

a = 'one'  
b = /#{a}/  
a = 'two'  

b不会更改(保持/one/)。我错过了什么?

1 个答案:

答案 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

所以我想这对于编译器而言是一件事,对于多次执行的行。