simPod
simPod

Reputation: 13456

Regex - prevent certain string from match

I'm trying to match a bank account number. It can be in this format: ########## or ######-##########

I started with this regex (\d{1,6}\-)?\d{2,10}. It should match 1. and 2. row, not 3. and 4. This regex matches 1. 2. and 4. How can I exclude 4., meaning prevent matching 000000?

  1. 100000-1234567890
  2. 1234567890
  3. -1234567890
  4. 000000-1234567890

Upvotes: 1

Views: 1870

Answers (2)

cFreed
cFreed

Reputation: 4474

The Wiktof Stribizew's answer is "the" good one.
But if you want to avoid headaches with lookahead you can merely use this:

^(?:[1-9](?:\d{1,5})?-)?\d{2,10}$

Here we simply forbid an initial "0" in the first group, then allow only till 5 other digits.

Demo here.

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

You can use a regex with a negative lookahead that will make sure the code with all zeros at the start is not matched:

^(?:(?!0+-)\d{1,6}-)?(?=\d*[1-9])\d{2,10}$

See the regex demo

Here,

  • ^ - matches the start of the string
  • (?:(?!0+-)\d{1,6}-)? - matches optionally (one or zero times, due to (?:...)? construct) a 1 to 6 digits (with \d{1,6}) followed with a hyphen only if the digits up to the - are not zeros (thanks to the negative lookahead (?!0+-))
  • (?=\d*[1-9]) - the second group of 2 to 10 digits should have at least 1 non-zero digit
  • \d{2,10} - matches 2 to 10 any digits followed with...
  • $ - end of the string

Basically, you just need two things to add to your regex:

  • anchors (^ and $)
  • and the lookahead

Upvotes: 4

Related Questions