Home > Mobile >  Extracting the digit between parentheses in Python
Extracting the digit between parentheses in Python

Time:10-10

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related