Eon
Eon

Reputation: 3984

Exclude a combination of characters in Regex (if the combination is found, the regex should fail)

I am attempting to write a regex to validate a sequence of numbers, and the regex should consist only of numbers- where the only rule is that the numbers 0049 is not allowed to be at the start of the sequence. The sequence is also restricted to only be 10 to 15 characters in length

Examples:

0049123456789 - Must Fail
0321123456789 - Allowed to succeed

The issue I am facing is that I am unsure how to force-fail the regex if the sequence '0049' is found in the first 4 positions in the character string. Here are some patterns I have tried.

Example number used: 0049123456789

^(^0049)|^(\d{10,15}+)$ - Matched against 0049, the regex validates as success

^((?<!(0049))|(\d{10,15}+))$ - both of the regex alternative capturing groups succeeded ((?<!(0049)) and (\d{10,15}+), validating the entire input as a successful input

^([^0049])|^(\d{10,15}+)$ - The second capturing group (\d{10,15}+) marks the combination of numbers as a success since it conforms to the rule of being numbers only, within a length of 10 - 15 characters.

I have never been any good with regexes - how can I force fail the combination of numbers 0049123456789 - just because 0049 is found at the start of the sequence?

Upvotes: 2

Views: 6939

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

You can use the following regex:

^(?!0049)\d{10,15}$

See regex demo

Regex breakdown:

  • ^ - start of string
  • (?!0049) - a negative lookahead checking if there is 0049 right after the beginning of string - and if found, no match is returned
  • \d{10,15} - 10 to 15 digits
  • $ - end of string.

Your regexps:

  • ^(^0049)|^(\d{10,15}+)$ - Matched against 0049 because you asked it to match 0049 at the beginning of the string (both ^ in ^(^0049) are start-of-string anchors)

  • ^((?<!(0049))|(\d{10,15}+))$ - matches since ^((?<!(0049)) means match if the start of string is not preceded with 0049

  • ^([^0049])|^(\d{10,15}+)$ - matches as the 2nd alternative finds a match, you are right. However, note that [^0049] is a negated character class matching any character but 0, 4 and 9 (it does not "negate" a sequence of digits).

Upvotes: 3

nu11p01n73R
nu11p01n73R

Reputation: 26677

Negative look aheads will be useful here

/^(?!0049)[0-9]{10,15}$/
  • ^ Anchors the regex at the start of the string.

  • (?!0049) Negative look ahead, checks if the start of the string is not 0049

  • $ Anchors the regex at the end of the string

Regex Demo

Upvotes: 3

Related Questions