JustMe
JustMe

Reputation: 455

How to get multiple substrings from a matching string?

I am trying to extract some text from a string, in which I need to use a two level matching.

I have a string like

  s="Text_1 is abc: and Text_2 is def: also Text_3 is ghi:"

The result should be a list of the Text_x content like

  result = ['abc', 'def', 'ghi']

Is there a way to use it with a single match/search using brackts or similar to

 x= re.compile('Text_\d (\w+)\:')
 l = x.match(s)

I could not get it proper resolved.

I am using python 3.9

Upvotes: 2

Views: 69

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521239

We can try using re.findall here:

s = "Text_1 is abc: and Text_2 is def: also Text_3 is ghi:"
matches = re.findall(r'\bText_\d+ is (\w+(?: \w+)*):', s)
print(matches)  # ['abc', 'def', 'ghi']

Upvotes: 1

Related Questions