首页 > 解决方案 > Ruby regex 获取由句点分隔的单词组合

问题描述

我正在尝试使用 Ruby 正则表达式来获得如下所示的单词组合。在下面的示例中,我只需要案例 1-4,* 将它们标记为大写以便于测试。中间的单词 ( dbo, bcd) 可以是与 case#3 类似的任何内容或任何内容。我很难让那个双周期案例#3 工作。也可以SALES作为单词独立使用,但对于一个正则表达式 ?Tx all guru 来说可能太多了。这是我部分工作的脚本,需要添加alpha..SALES

 s = '1 alpha.dbo.SALES    2 alpha.bcd.SALES    3 alpha..SALES    4 SALES
      bad cases 5x alpha.saleS  6x  saleSXX'

 regex = /alpha+\.+[a-z]+\.?sales/ix
 puts 'R: ' + s.scan(regex).to_s

##R: ["alpha.dbo.SALES", "alpha.bcd.SALES"]

标签: rubyregex

解决方案


r = /
    (?<=\d[ ])        # match a digit followed by a space in a positive lookbehind
    (?:               # begin a non-capture group
      \p{Alpha}+        # match one or more letters
      \.                # match a period
      (?:               # begin a non-capture group
        \p{Alpha}+      # match one or more letters
        \.              # match a period
        |               # or
        \.              # match a period
      )                 # end non-capture group
    )?                  # end non-capture group and optionally match it
    SALES             # match string
    (?!=[.\p{Alpha}]) # do not match a period or letter (negative lookahead)
    /x                # free-spacing regex definition mode.

s.scan(r)
  #=> ["alpha.dbo.SALES", "alpha.bcd.SALES", "alpha..SALES", "SALES"]

这个正则表达式习惯上写成如下。

r = /
    (?<=\d )(?:\p{Alpha}+\.(?:\p{Alpha}+\.|\.))?SALES(?!=[.\p{Alpha}])/

在自由间距模式下,空格必须放在字符类 ( [ ]) 中;否则它将被剥离。


推荐阅读