How to include a substring EXCEPT an exact one in middle of REGEX expression?

Viewed 33

Issue

I'm trying to match 3 groups, where one is conditional

String: 12345-12345-1230

Group 1: 12345-12345

Group 2: -123

Group 3: 0

However I only want to match Group 2 if the string is NOT "-000". Meaning group 2 will either be blank if that section is '-000' or it will be whatever else those 4 characters are; '-123' '-001', etc.).

Here is the REGEX with it just accepting anything as group 2: ^(.{5}-.{5})(.{4})([0-9])$ regex101

What I've tried

Negative Lookahead:

  • ^(.{5}-.{5})(?!-000)([0-9])$
  • ^(.{5}-.{5})(.{4}(?!.{4}))([0-9])$

OR Operator:

  • ^(.{5}-.{5})(-000)|(.{4})([0-9])$
  • This is the closest I've come, however I can't get it to work WITH the final condition ([0-9])$. It's also not ideal to have the remove case (-000) as a separate group as the accept case (not -000).
2 Answers

You may try:

^(\d{5}-\d{5})(?:-000|(-\d{3}))(\d)$

See the online demo.


  • ^ - Start of line ancor.
  • ( - Open 1st capture group.
    • \d{5}-\d{5} - Match 5 digits, an hyphen, and again 5 digits.
    • ) - Close 1st capture group.
  • (?: - Open non-capturing group.
    • -000 - Match "-000" literally.
    • | - Pipe symbol used as an or-operator.
    • ( - Open 2nd capture group.
      • -\d{3} - match an hyphen and 3 digits.
      • ) - Close 2nd capture group.
    • ) - Close non-capturing group.
  • ( - Open 3rd capture group.
    • (\d) - Match a single digit.
    • ) - Close 3rd capture group.
  • $ - End line ancor.

If you want to capture the 2nd group without hypen, then try: ^(\d{5}-\d{5})-(?:000|(\d{3}))(\d)$

Try this:

(\d{5}-\d{5})(?!-000)(-\d{3})(0)

See Demo

Related