tomsam
tomsam

Reputation: 49

RegEx, string contains at least 2 number between 1 and 9

I have a 9 digit number where last 4 is optional (5+4). I want to say that there should be AT LEAST TWO [1-9] values (regardless of the position) in the first 5 character

Working Examples: 26505, 00230, 00021, 23010
Failing Examples: 20000, 02000

I built this, but not working the way that I want:

^(?=[1-9]{0,4}\d)\d{5}(-?\d{4})?$

Upvotes: 2

Views: 1546

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

For the majority of regex engines, there is no generic, easily expandable regex solution. In this case, you can spell out all possible combinations like in

^(?!0{5}|0{4}[1-9]|0{3}[1-9]0|0{2}[1-9]0{2}|0[1-9]0{3}|[1-9]0{4})\d{5}(?:-?\d{4})?$
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

See the regex demo where the negative lookaheads fails the match if the first 5 digits only contain 1 1-9 digit and others are zeros.

However, if you have more than 5 digits to check for, say 50, that will become unwieldly.

A generic regex solution is possible in case your regex supports an infinite-width lookbehind (.NET, Python PyPi regex module), you may use

^\d{5}(?<=^\d*(?:[1-9]\d*){2})(?:-?\d{4})?$

See this regex demo

The (?<=^\d*(?:[1-9]\d*){2}) lookbehind will require 2 1-9 digits anywhere between the start of string and the 5th digit.

Upvotes: 1

A_Elric
A_Elric

Reputation: 3568

I think that my regex using a positive lookbehind is a bit easier and a lot more readable.

(\d{5})(?<=[1-9]{2})-(\d+)

Live example: https://regex101.com/r/CnEw7Z/2

Explanation -- There will be a set of 5 numbers, this has to have 2 characters between 1 and 9 in the field that matches \d{5} followed by a hyphen and some other numbers (\d+)

Let me know if this makes sense / works for you, and feel free to adjust capture groups to your liking.

Upvotes: 0

Related Questions