3
votes

If I had a sentence that has an age and a time :

import re
text = "I am 21 and work at 3:30"
answer= re.findall(r'\b\d{2}\b', text)
print(answer)

The issue is that it gives me not only the 21, but 30 (since it looks for 2 digits). How do I avoid this so it will only count the numbers and not the non-alphanumeric characters that leads to the issue? I tried to use [0-99] instead of the {} braces but that didn't seem to help.

4
Sorry, the answer it gives is 21 and 30 (the 3:30) using only the last two digits in the time. - netrate
Edit it on your main text rather than put it in the comment. Not all people read comments. - Tai
What do you mean by "How do I avoid this so it will only count the numbers and not the non-alphanumeric characters "? "non-alphanumeric characters"? - Tai
i believe this is not your actual problem. what's your real problem? for example, do you want to catch 2 digits at the beginning of a string or at the end of one? - Jason Hu
This does not match any non-numerical characters so you entire premise must be wrong. - Jongware

4 Answers

4
votes

Using \s\d{2}\s will give you only 2 digit combinations with spaces around them (before and after).

Or if you want to match without trailing whitespace: \s\d{2}

2
votes

Thats because : is considered as non-word constituent character when you match empty string at word boundary with \b. In Regex term, a word for \b is \w+.

You can check for digits with space or start/end of input line around:

(?:^|\s)(\d{2})(?:\s|$)

Example:

In [85]: text = "I am 21 and work at 3:30"
    ...: re.findall(r'(?:^|\s)(\d{2})(?:\s|$)', text)
Out[85]: ['21']
2
votes

You can use (?<!)(?!) negative lookahead to isolate and capture only 2 (two) digits.

Regex: (?<!\S)\d{2}(?!\S)

1
votes

You can use the following regex:

^\d{2}$|(?<=\s)\d{2}(?=\s)|(?<=\s)\d{2}$|^\d{2}(?=\s)

that will match all the 21 in the following strings:

I am 21 and work at 3:30
21
abc 12:23
12345
I am 21
21 am I

demo: https://regex101.com/r/gP1KSf/1

Explanations:

  1. ^\d{2}$ match 2 digits only string or
  2. (?<=\s)\d{2}(?=\s) 2 digits surrounded by space class char or
  3. (?<=\s)\d{2}$ 2 digits at the end of the string and with a preceded by a a space class char
  4. ^\d{2}(?=\s) 2 digits at the beginning of the string and followed by a space class char