2

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

martineau
  • 119,623
  • 25
  • 170
  • 301
JustMe
  • 366
  • 1
  • 4
  • 14
  • Does this answer your question? [RegEx with multiple groups?](https://stackoverflow.com/questions/4963691/regex-with-multiple-groups) – AlexisG Mar 01 '22 at 11:00

1 Answers1

1

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']
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360