CarefullyAdvanced
CarefullyAdvanced

Reputation: 467

Retrieve matching strings from text file

I have the following text file and I want to retrieve the numbers in brackets

ID&number:Track_number(12930)_
ID&number:Track_number(394839)_
ID&number:Track_number(958236)_

So I've tried this

 import re

 file = open("text.txt", "r")
 text = file.read()
 file.close()
 pattern = re.compile(ur'Track_number(.*)_', re.UNICODE)
 string = pattern.search(text).group(1)
 print string

But it only displays the first result : (12930). I was wondering if it was possible to have a list of all the matching results. Thanks

Upvotes: 4

Views: 78

Answers (2)

TigerhawkT3
TigerhawkT3

Reputation: 49320

All you have to do is replace that search with findall. This will produce a list of all the matches.

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117856

You can use re.findall for example

>>> re.findall('\((\d+)\)', text)
['12930', '394839', '958236']

Upvotes: 2

Related Questions