分割多行 Ruby 正则表达式

这可能不是你想要的问题!我不希望正则表达式与换行符相匹配; 相反,我希望编写一个长的正则表达式,为了便于阅读,我希望将其分割成多行代码。

比如:

"bar" =~ /(foo|
bar)/  # Doesn't work!
# => nil. Would like => 0

能做到吗?

30151 次浏览

You need to use the /x modifier, which enables free-spacing mode.

In your case:

"bar" =~ /(foo|
bar)/x

you can use:

"bar" =~ /(?x)foo|
bar/

Using %r with the x option is the prefered way to do this.

See this example from the github ruby style guide

regexp = %r{
start         # some text
\s            # white space char
(group)       # first group
(?:alt1|alt2) # some alternation
end
}x


regexp.match? "start groupalt2end"

https://github.com/github/rubocop-github/blob/master/STYLEGUIDE.md#regular-expressions

Rather than cutting the regex mid-expression, I suggest breaking it into parts:

full_rgx = /This is a message\. A phone number: \d{10}\. A timestamp: \d*?/


msg = /This is a message\./
phone = /A phone number: \d{10}\./
tstamp = /A timestamp: \d*?/


/#{msg} #{phone} #{tstamp}/

I do the same for long strings.

regexp = %r{/^
WRITE
EXPRESSION
HERE
$/}x