如何修复非贪婪的正则表达式

时间:2014-11-06 23:10:21

标签: python regex

word = "\W*?[^,\t ]*?\W*?"
quotedSelectedWord = "\W*?\"(.*?)\"\W*?"
leftCurlyBrace = "\W*?\{\W*?"
rightCurlyBrace = "\W*?\}\W*?"
expression = leftCurlyBrace + word + "," + quotedSelectedWord

p = re.compile(expression)

for line in sourceFileList:
    line = line.strip()
    if (p.match(line)):         
        temp1 = p.sub(r"\1", line);
        print "temp1 = " + temp1 + "\n"

如果第一行是(没有实际的单引号): '{_blah_blah,'blah-blah“,”blah blah blah“,false,false,{_blah},”“},'

为什么temp1 ='blah-blah,'blah blah blah“,false,false},'?

我认为这相当于括号中的第一个“小组”,我认为这将是“等等”。

2 个答案:

答案 0 :(得分:2)

正则表达式找到的模式不是一次而是两次。

它找到的第一个是:

{_blah_blah, "blah-blah"

在这种情况下,group(1)(上面括号中的部分)是blah-blah,正如您所确定的那样,它用来替换字符串的第一部分。

但它也在这里找到了模式:

, {_blah}, ""

此处group(1)仍在寻找.*?,是一个空字符串。所以它没有任何东西替换字符串的那部分,有效地删除它。

This site帮我解决了这个问题。

这里有site,显示找到了这两个匹配项:

正确的link和正则表达式。

enter image description here

更新

此网站在解析正则表达式时更有帮助:http://regex101.com/#python

在此站点上,输入正则表达式。重要的一点是在其右侧输入g修饰符以获取所有匹配项。接下来输入测试字符串和\1的替代。它已经显示了匹配和替换。这很好。现在左键单击"正则表达式调试器"。

enter image description here

如果您展开此部分,您将能够确切地了解它是如何找到这两个匹配项的:

enter image description here

答案 1 :(得分:1)

re.sub(pattern, repl, string, count=0, flags=0)

python documentation个州
  

返回通过替换repl替换字符串中最左边非重叠模式而获得的字符串。

如果我们重写一下for循环:

for line in sourceFileList:
    line = line.strip()
    match = p.match(line)
    if (match):
        print "whole match = " + match.group()
        print "first group = " + match.group(1)
        temp1 = p.sub(r"\1", line)
        print "temp1 = " + temp1 + "\n"

我们得到输出:

whole match = {_blah_blah, "blah-blah"
first group = blah-blah
temp1 = blah-blah, "blah blah blah", false, false},

这意味着{_blah_blah, "blah-blah"将被原始字符串中的blah-blah替换,最后仍包含, "blah blah blah", false, false, {_blah}, ""},

如果您只想获得第一个捕获组,可以使用group(1),如上所示。

修改

正如twasbrillig的回答所指出,有两个替代品。如果使用re.sub调用count = 0或省略count参数,则会替换所有出现的模式,而不仅仅是第一个模式。


附注:我建议在模式中使用原始字符串:

word = r"\W*?[^,\t ]*?\W*?"