-1

I'm trying to fetch the numbers within the last bracket of each line in a block of text. However, my current approach only fetch me the numbers of the last bracket.

I've tried with (the numbers may be of any digit):

import re

items = """
PTT KBALTHNAL (07) PETROL STATION (500003985)
ZHONGGUO (035) SHAXIAN 01 (5001039)
AHARATHAN BAIJIAING (0837) SU YOUMING (500086)
"""
ids = re.findall(r"\((\d+)\)$",items)
print(ids)

Output I get:

['500086']

Output I'm after:

['500003985','5001039','500086']

How can I extract the numbers from the last bracket of each line?

asmitu
  • 175
  • 11

1 Answers1

1

Lets do this by including only the last brackets of the string :

items = 'PTT KBALTHNAL (07) PETROL STATION (500003985)\nZHONGGUO (035) SHAXIAN 01 (5001039)\nAHARATHAN BAIJIAING (0837) SU YOUMING (500086)'

Here (?!.) excludes every occurences just after newline:

re.findall('\((\d+)\)(?!.)',items)

Here, we find digits with brackets,ending by new-line.
this gives you:

['500003985', '5001039', '500086']
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34