Home > Software design >  Regex code to match string start and end position, but exclude specific matches
Regex code to match string start and end position, but exclude specific matches

Time:03-28

Can someone help, please! I have a list of account numbers, below is an example of the formats. Essentially all accounts start with "DO", they then have four numbers, they then have a sibling account with an "M" on the end and another with a "PY". DO1200, DO1200M, DO1200PY

I want to identify all accounts that end in "M" and have the following code to do that.

^DO.\[M\]$

I have 3 accounts I want to exclude from this list, DO1210M, DO1215M & DO1220M and I haven't been able to find an answer.

I've tried searching StackOverflow for other answers such as:

^/(?!DO1210M|DO1215M|DO1220M)(\[a-z0-9\] )$

And trying to add this into my code, and while some of my attempts still retrieve results they never actually exclude the accounts I'm trying to exclude.

CodePudding user response:

You can use a negative lookahead with a non capturing group:

^(?!(?:DO1210M|DO1215M|DO1270M)$)^DO\d{4}M$
^                                ^              #beginning of the line
                               $          $     #end of line
 (?!                            )               #negative lookahead
    (?:                       )                 #non capturing group
              |       |                         #logical OR
       XXXXXXX XXXXXXX XXXXXXX                  #text not to match
                                  DO     M      #Literal text
                                    \d          #any digit
                                      {4}       #quantifier, exactly 4 times

Example

  • Related