Reputation: 408
I have searched for similar questions, and even though I found several answers, none seams to work. I have a list of strings
Z189
I142
M395
L210
V467
M203
Q277
Q461
Y440
S250
M162
Q96
22Q
W148
Q72
T22T
22TWE22
12E34
and I need a regex to find only strings holding only 2 digits (not more or less). So in this case:
Q96, 22Q, Q72, T22T
my failed attempts include:
\D\d{2}\D
(?<!\d)\d{2}(?!\d)
Upvotes: 2
Views: 3994
Reputation: 12880
You could use ^\D*(\d)\D*(\d)\D*$
\D*
makes sure anything before your first digit isn't another digit.
(\d)
captures your first digit.
\D*
makes sure there is no other digits between your two digits.
(\d)
captures your second digit.
\D*
makes sure anything after your second digit isn't another digit.
Upvotes: 6
Reputation: 6111
You didn't mention if the digits had to be sequential, but all of your examples had them as such. The following RegEx will only match lines that contain exactly two sequential digits:
^\D*\d{2}\D*$
Explained:
^
matches the beginning of the String\D*
matches any non-digit zero or more times\d{2}
matches exactly two digits\D*
matches any non-digit zero or more times$
matches the end of the StringFiddle: Live Demo
Upvotes: 2
Reputation:
This works well. Note the global
and multiline
flags.
/^[a-zA-z]\d{2}[a-zA-Z]*$/gm
Explanation: Start of line -> letter -> exactly two digits -> zero or more letters -> end of line
Upvotes: 2
Reputation: 626853
To match a string that only contains 2 digits at any location, you may use
^\D*(?:\d\D*){2}$
See the regex demo
Details
^
- start of string\D*
- any 0+ chars other than digits(?:\d\D*){2}
- 2 repetitions of:
\d
- a digit\D*
- any 0+ chars other than digits$
- end of string.Upvotes: 2