如何从左到右运行贪婪的正则表达式

时间:2018-11-01 09:10:23

标签: python regex

我有以下要匹配的字符串:

"data data and some stuff in the middle that can change, data data"

现在,如果我只想一次在字符串末尾提取“数据”,那么我将使用惰性的量词:

data\s.+?data

符合条件的

"data data and some stuff in the middle that can change, data"

我该如何执行从左到右的相同操作,所以我只在字符串的开头一次拾取“数据”?

我使用的是Python风格,以防有人需要知道。

1 个答案:

答案 0 :(得分:1)

您有两个选择。第一种是使用捕获组:

^\s*(?:data\s+)*(data\s.*?data)

请参见live demo here

您需要的是第一个捕获组。第二种方法是在两端用一个data替换重复的data,方法是:

^(?:\s*data)+|(data\s*)+$

请参见live demo here