Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 具有条件处理的Groovy正则表达式增强_Regex_Groovy - Fatal编程技术网

Regex 具有条件处理的Groovy正则表达式增强

Regex 具有条件处理的Groovy正则表达式增强,regex,groovy,Regex,Groovy,我需要增强此应用程序的正则表达式,以满足以下要求 当前的正则表达式如下所示 ^[CDFGIMP][^_\\s]*_\\S*$ 以下代码将是有效的 C_12345 需要对其进行调整,以接受以下情况 新的正则表达式格式应至少包含2个下划线 例外:如果代码以“M”开头,则它只能包含至少一个下划线 FKT12965_I20_GB215_01 FKN16250_I26_GB215_03 FKT12808_I09_GB215_01 CQ425441_I09_GB214_01 我相信您可以使用: de

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

当前的正则表达式如下所示

^[CDFGIMP][^_\\s]*_\\S*$
以下代码将是有效的

C_12345

需要对其进行调整,以接受以下情况

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

  • FKT12965_I20_GB215_01

  • FKN16250_I26_GB215_03
  • FKT12808_I09_GB215_01
  • CQ425441_I09_GB214_01

我相信您可以使用:

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)

不过,我倾向于将这类事情拉到实际的代码中,因为下一个必须查看此代码的人会有暴力的想法

与@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)

到目前为止,您尝试了什么?(^[CDFGIP][^\s]*\s*$)(^[M][^\s]*)-尝试将其按此方式分组({2})-类似于这样的方式以确保有两个下划线?尝试它几乎在那里-如果它是CDFGIP-那么它至少需要包含两个下划线