Exclusion matching the regular expression

I’m just venturing into regular expressions and I have a problem that I can’t solve.

I have to create a regular expression that matches the string “M6” which however I can find formatted in different ways.

Currently the expression I created is: /[mM]0?6[tT \r\n]+/
The problem I can’t solve is that I always have to exclude the match if I have a ‘;’ character before the matched string in any position or a ‘(‘ without the corresponding ‘)’.

I thought I could use the negative Lookbehind but the problem is that the ‘;’ can be positioned in different places and not always in the same way.

I leave some examples of how the string to match may appear:

N30 M06 T10 match

M6 T11 match

T12 M6 (T2 tool change) match

N2878 T3 M06 match

;N1029 T3 M06 not match

**N224 ;T10 M06 not match

(M6T12) not match

T11 M62 not match

How can I solve it?
Thank you

I tried inserting an exclusion into the regular expression but without getting the results as follows:

/.*[^;(].*[mM]0?6[tT \r\n]+/

^[^;]*\b(M0?6)\b

  • ^[^;]* Start of string has any number of characters that arent ;
  • \b(M0?6)\b matches M06 or M6 as a word (i.e. between word boundary characters) and captures it (optional)

If you’re using the multiline specifier flag, you’ll need to adapt it: ^[^;\n]*\b(M0?6)\b

Leave a Comment