Reputation: 13456
I'm trying to match a bank account number.
It can be in this format:
##########
or ######-##########
######-
), if present, can have 1-6 numbers followed by -
and all of them can't be zeros. It can match 123456-
but can't 000000-
##########
) can have 2-10 numbers, there must be one no zero characterI 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
?
Upvotes: 1
Views: 1870
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.
Upvotes: 1
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 stringBasically, you just need two things to add to your regex:
^
and $
) Upvotes: 4