0
import re    
print(re.search('\(\d{1,}\)', "b'   1. Population, 2016 (1)'"))

I am trying to extract the digits (one or more) between parentheses in strings. The above codes show my attempted solution. I checked my regular expression on https://regex101.com/ and expected the codes to return True. However, the returned value is None. Can someone let me know what happened?

  • [`\(\d+\)`](https://regex101.com/r/gg5mj7/1) that's right, isn't it? or `(?<=\()\d+(?=\))` – wnull Oct 10 '22 at 05:27

2 Answers2

3

Your current regex pattern is only valid if you make it a raw string:

inp = "b'   1. Population, 2016 (1)'"
nums = re.findall(r'\((\d{1,})\)', inp)
print(nums)  # ['1']

Otherwise, you would have to double escape the \\d in the pattern.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

Below RE will help you grab the digits inside the brackets only when the digits are present.

r"\((?P<digits_inside_brackets>\d+)\)

For your scenario, the above RE will match 1 under the group "digits_inside_brackets". It can be executed through below snippet

import re
user_string = "b'   1. Population, 2016 (1)"
comp = re.compile(r"\((?P<digits_inside_brackets>\d+)\)") # Captures when digits are the only 
for i in re.finditer(comp, user_string):
    print(i.group("digits_inside_brackets"))

Output for the above snippet

Grab digits even when white space are provided:

r"\(\s*(?P<digits_inside_brackets>\d+)\s*\)

Grab digits inside brackets at any condition:

r"\(\D*(?P<digits_inside_brackets>\d+)\D*\)

Output when applied with above RE