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

标签 ruby regex

Ruby 正则表达式有一些选项(例如 ixmo)。例如,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/

相关文章:

Java 正则表达式 - 如何获取符号之间的单词

ruby - 如何为函数内的全局变量赋值?

ruby - 如何在 Ruby 脚本中运行 Rake 任务?

ruby - 从 Ruby 执行 PowerShell

Java : split string to char array using regex

java - 如何找到两个相邻的重复数字并将它们替换为Java中的单个数字?

ruby-on-rails - 我想知道 Ruby 或 Ruby on Rails(框架)中是否有 Head- and Tail-methods

ruby-on-rails - rails 3.2 使用的默认 gem

python - 类似的字符串,并希望在 python 中使用 RegEx、Pandas 创建 3 个单独的数据帧

regex - 如何将 "lastname, firstname"拆分为单独的字符串?