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
  • 112,593
  • 23
  • 157
  • 280
JustMe
  • 154
  • 2
  • 12
  • 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
  • 451,927
  • 24
  • 239
  • 318