I'm trying to find a number which is in the range 1 to 34 in my string but not getting the expected output. Code:
re.findall("(\d[1-34])","hi34hi30hi12")
Output:
['34','12']
Where is 30 here?? Or am I doing it wrong??
I'm trying to find a number which is in the range 1 to 34 in my string but not getting the expected output. Code:
re.findall("(\d[1-34])","hi34hi30hi12")
Output:
['34','12']
Where is 30 here?? Or am I doing it wrong??
That regex is wrong.
As it's been said in a comment above, your regex will match a single digit \d
, followed by a single character in the set {1,2,3,4} which is the explicit meaning of the character class you used [1-34]
This one matches all the 2 digit numbers from 00 to 34 :
re.findall("([0-2][0-9]|3[0-4])","hi34hi30hi12")
this expression is made of two parts : the first
[0-2][0-9]
matches two characters, the first be a 0, a 1 or a 2 and the second a numerical digit; the second part is alternative the the first match (using the |
operator)
3[0-4]
and matches a 3 followed by a 0, a 1, a 2, a 3 or a 4.
That expression, thus, as required, matches all 2 digit numbers from 00 to 34.
\d[1-34]
actually matches a digit, followed by a digit that's in the range 1-3, or an "4".
"34" was matched because \d
matched 3, and then the 4 inside the character class matched the 4.
"12" was matched because, again, \d\
matched 1, and then 2 was matched because it's in the range 1-3.
As mentioned in the comments, a better solution would be matching all 2-digit numbers and verify the range manually:
>>> re.findall("(\d\d)","hi34hi30hi12")
['34', '30', '12']
Now iterate over the list and verify the range.