-1

I need to enhance the regex for this application to satisfy the following.

The current regex looks like this

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

and the following code will be valid

C_12345

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

it needs to be adapted to accept the following cases

  • The new ReGex format should contain at least 2 underscores
  • Exception: if the code begin with 'M' then it only must contain at least one underscore

  • FKT12965_I20_GB215_01

  • FKN16250_I26_GB215_03
  • FKT12808_I09_GB215_01
  • CQ425441_I09_GB214_01
The Old County
  • 109
  • 7
  • 40
  • 99

2 Answers2

0

Just a slight variation to the answer from @tim-yates and with comments:

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)
Paul King
  • 524
  • 3
  • 6
-1

I believe you could use this:

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)

I tend to prefer to pull this sort of thing out into actual code though, as the next person who has to look at this code will have thoughts of violence

tim_yates
  • 154,107
  • 23
  • 313
  • 320