'Regex for two digits in any order
I need a regex that will match a string as long as it includes 2 or more digits.
What I have:
/(?=.*\d)(?=.*\d)/
and
/\d{2,}/
The first one will match even if there is one digit, and the second requires that there are 2 consecutive digits. I have tried to combine them in different ways to no avail.
Solution 1:[1]
You can do much simpler :
/\d\D*\d/
Solution 2:[2]
You can use the following expression:
.*\d.*\d.*
This will match anything that has two digits in it, anywhere. Regardless of where the numbers are. Example here.
You can also do it like this, using ranges:
.*[0-9].*[0-9].*
You may also consider using this:
\D*\d\D*\d
The \D
will match anything that is not a digit character
Solution 3:[3]
It depends on your applications language, but this regex is the most general:
^(?=.*\d.*\d)
Not all application languages consider partial matches as "matching"; this regex will match no matter where in the input the two digits lie.
Solution 4:[4]
grep -E ".*[0-9].*[0-9].*" filename
Solution 5:[5]
You can use the following depending on the use case:
^(?=(?:\D*\d){2}).*
- The restriction is implemented with a positive lookahead (anchored at the start of string) that requires any two (or more) digits anywhere inside the string (and the regex flavor supports lookaheads) - Regex demo #1^([^0-9]*[0-9]){2}.*
- The regex matches a string that starts with two sequences of any non-digit chars followed with a digit char and then contains any text (this pattern is POSIX ERE compliant, to make it POSIX BRE compliant, use^\([^0-9]*[0-9]\)\{2\}.*
) - Regex demo #2\d\D*\d
- in case you simply want to make sure there is a digit + zero or more chars other than digits followed with a digit and the method you are using allows partial matches - Regex demo #3.
The first approach is best when you already have a complex pattern and you need to add an extra constraint.
The second one is good for POSIX regex engines.
The third one is best when you implement complex if-else logic for password and other validations with separate error messages per issue.
Solution 6:[6]
try this. [0-9].{2}
this will help to u
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Jerry |
Solution 3 | Bohemian |
Solution 4 | |
Solution 5 | Wiktor Stribiżew |
Solution 6 |