将 Ruby 正则表达式拆分为多行
这可能不是您所期待的问题!我不想要一个能够匹配换行符的正则表达式;相反,我想编写一个很长的正则表达式,为了便于阅读,我想将其拆分为多行代码。
比如:
"bar" =~ /(foo|
bar)/ # Doesn't work!
# => nil. Would like => 0
可以做到吗?
This might not be quite the question you're expecting! I don't want a regex that will match over line-breaks; instead, I want to write a long regex that, for readability, I'd like to split onto multiple lines of code.
Something like:
"bar" =~ /(foo|
bar)/ # Doesn't work!
# => nil. Would like => 0
Can it be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将 %r 与 x 选项一起使用是执行此操作的首选方法。
请参阅 github ruby 样式指南
https:// github.com/github/rubocop-github/blob/master/STYLEGUIDE.md#regular-expressions
Using %r with the x option is the prefered way to do this.
See this example from the github ruby style guide
https://github.com/github/rubocop-github/blob/master/STYLEGUIDE.md#regular-expressions
您需要使用
/x
修饰符,它启用自由间距模式< /a>.在你的情况下:
You need to use the
/x
modifier, which enables free-spacing mode.In your case:
我建议不要切割正则表达式中间表达式,而是将其分成几部分:
我对长字符串执行相同的操作。
Rather than cutting the regex mid-expression, I suggest breaking it into parts:
I do the same for long strings.
你可以使用:
you can use: