将 Ruby 正则表达式拆分为多行

发布于 2024-09-24 12:06:57 字数 212 浏览 3 评论 0原文

这可能不是您所期待的问题!我不想要一个能够匹配换行符的正则表达式;相反,我想编写一个很长的正则表达式,为了便于阅读,我想将其拆分为多行代码。

比如:

"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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

故乡的云 2024-10-01 12:06:57

将 %r 与 x 选项一起使用是执行此操作的首选方法。

请参阅 github ruby​​ 样式指南

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

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

梦亿 2024-10-01 12:06:57

您需要使用 /x 修饰符,它启用自由间距模式< /a>.

在你的情况下:

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

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

In your case:

"bar" =~ /(foo|
           bar)/x
凑诗 2024-10-01 12:06:57

我建议不要切割正则表达式中间表达式,而是将其分成几部分:

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}/

我对长字符串执行相同的操作。

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.

姜生凉生 2024-10-01 12:06:57

你可以使用:

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

you can use:

"bar" =~ /(?x)foo|
         bar/
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文