如何从匹配的字符串中获取多个子字符串?

How to get multiple substrings from a matching string?

提问人:JustMe 提问时间:3/1/2022 最后编辑:martineauJustMe 更新时间:3/1/2022 访问量:56

问:

我正在尝试从字符串中提取一些文本,其中我需要使用两级匹配。

我有一个像这样的字符串

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

结果应该是Text_x内容的列表,例如

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

有没有办法将它与使用 brackts 或类似

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

我无法正确解决它。

我正在使用 python 3.9

搜索 匹配 python-re

评论

0赞 AlexisG 3/1/2022
这回答了你的问题吗?具有多个组的正则表达式?

答:

1赞 Tim Biegeleisen 3/1/2022 #1

我们可以在这里尝试使用:re.findall

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']