带条件处理的Groovy正则表达式增强

时间:2018-11-01 10:52:02

标签: regex groovy

我需要为此应用程序增强正则表达式,以满足以下要求。

当前正则表达式如下

^[CDFGIMP][^_\\s]*_\\S*$

,以下代码将有效

C_12345

https://regex101.com/r/x2jUnt/2

需要适应以下情况

  • 新的ReGex格式应至少包含2个下划线
  • 例外:如果代码以“ M”开头,则它必须至少包含一个下划线

  • FKT12965_I20_GB215_01

  • FKN16250_I26_GB215_03
  • FKT12808_I09_GB215_01
  • CQ425441_I09_GB214_01

2 个答案:

答案 0 :(得分:0)

与@ tim-yates的答案略有不同,并带有注释:

def regex = /(?x)           # to enable whitespace and comments
             ^              # match from beginning
               (            # start of alternative 1
                 [CDFGIP]   # starts with one of CDFGIP
                 [^_\s]*    # zero or more non-underscore non-whitespace chars
                 _          # an underscore
                 [^_\s]*    # zero or more non-underscore non-whitespace chars
                 _          # an underscore
                 \S*        # zero or more non-whitespace chars
               |            # start of alternative 2
                 M          # starts with M
                 [^_\s]*    # zero or more non-underscore non-whitespace chars
                 _          # an underscore
                 \S*        # zero or more non-whitespace chars
               )            # end of alternatives
             $              # match to end
/

assert "FKT12965_I20_GB215_01".matches(regex)
assert "MKT12965_I20".matches(regex)
assert !"C_12345".matches(regex)

答案 1 :(得分:-1)

我相信您可以使用:

def regex = /^([CDFGIP][^_\s]+_[^_\s]+_\S+|M[^_\s]+_\S+)$/

assert "FKT12965_I20_GB215_01".matches(regex)
assert "MKT12965_I20".matches(regex)
assert !"C_12345".matches(regex)

尽管如此,我还是倾向于将这类事情纳入实际代码中,因为下一个必须阅读此代码的人会想到暴力行为