什么是 Ruby 正则表达式中的“?-mix" [英] What is '?-mix' in a Ruby Regular Expression
问题描述
只是想在 ruby 中调试一个正则表达式.当我打印正则表达式的内容时,即使这些字符不是表达式的一部分,它也会在正则表达式的开头显示 ?-mix
.请参阅以下 IRB 输出以查看此说明
Just trying to debug a regular expression in ruby. When I print the contents of a regular expression, it shows ?-mix
at the beginning of the regular expression even though those characters were not part of the expression. Please see the following IRB output to see this illustrated
irb(main):028:0* EXPR = /^a$/
=> /^a$/
irb(main):029:0> EXPR
=> /^a$/
irb(main):030:0> puts EXPR
(?-mix:^a$)
=> nil
如您所见,当您使用puts
打印出正则表达式的内容时,开头是?-mix
.我应该担心这个吗?它来自哪里?
As you can see, when you use puts
to print out the contents of a regular expression, there is ?-mix
at the beginning. Should I be concerned by this? Where is it coming from?
推荐答案
mix
不是英文单词 mix,它是 Regexp
的选项.
mix
is not the English word mix, it's options of Regexp
.
参见Regexp#to_s
:
返回一个包含正则表达式及其选项的字符串(使用 (?opts:source
) 表示法.
Returns a string containing the regular expression and its options (using the (
?opts:source
) notation.
在您的示例中,m
用于多行模式,i
用于不区分大小写,x
用于扩展模式.破折号前的选项打开,后面的选项关闭(默认).问题的示例 ?-mix
已关闭所有选项.
In your example, m
is for multiline mode, i
is for case insensitive, and x
is for extended mode. Options before the dash are on, those after are off (default). The question's example, ?-mix
, has all options off.
您可以像这样打开它们:
You can turn them on like:
puts /^a$/mix
# =>(?mix:^a$)
这篇关于什么是 Ruby 正则表达式中的“?-mix"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!