【问题标题】:How to capture multiple substrings between two markers using regular expressions?如何使用正则表达式捕获两个标记之间的多个子字符串?
【发布时间】:2019-11-19 12:57:27
【问题描述】:

我知道如何在两个标记之间捕获子字符串的单个实例:

Python 3 How to get string between two points using regex?

我用这个字符串测试了这个方法:

text = 'blah.blah${capture1}.${capture2}'

我想获取这些标记“${”和“}”之间的所有子字符串,但它只获取第一个。

>>> text = 'blah.blah${capture1}.${capture2}'
>>> found = re.search('\$\{(.+?)\}', text)
>>> found.groups()
('capture1',)
>>> len(found.groups())
1
>>> 

我如何获得所有这些?

【问题讨论】:

    标签: python regex


    【解决方案1】:

    您需要一个正则表达式方法来查找字符串中的所有匹配项。你应该试试re.findall('\$\{(.+?)\}', text)re.finditer('\$\{(.+?)\}', text)。第一个将返回一个列表,第二个将返回一个可迭代对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-23
      • 2020-07-29
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多