【问题标题】:Python regex string match and replace at the same timePython 正则表达式字符串同时匹配和替换
【发布时间】:2019-10-14 00:35:35
【问题描述】:

在 Python 中,有没有办法同时搜索、返回匹配的字符串和替换匹配的字符串?请参见下面的示例:

a = "[fox] dog turtle [cat]"

目标:

result1 = "fox" #(first match inside bracket)
result2 = "cat" #(second match inside bracket)
result3 = "dog turtle" #(remaining string after removing matched text inside brackets

我有什么:

result1, result2 = re.findall('\[.*?\]', a)
result3 = re.sub('\[.*?\]', '', a)

运行re 两次似乎是多余且笨重的。有没有更优雅的方法来实现这一点?

【问题讨论】:

    标签: python regex python-3.x string replace


    【解决方案1】:

    我认为你的代码足够优雅和可读,但如果你想让事情复杂化,return 匹配的 function 不 并同时替换它们,但您可以使用re.sub 的力量 在 repl 参数中接受 function 接受匹配项作为参数和 应该返回一个str 替换,它用于动态替换 (example: when the replacing depends on the value of the match it self).

    import re
    
    a = '[fox] dog turtle [cat]'
    matches = []
    # append method of list return None so the return string is always `''`
    # so when ever we find a match to replace we add it to matches list and replace it with `''`
    # in your result you return the fox without brackets so i'm using a capture group inside the brackets
    text = re.sub('\[(.*?)\]', lambda m: matches.append(m.group(1)) or '', a)
    
    print(matches)  # ['fox', 'cat']
    print(text)  # dog turtle
    

    【讨论】:

    • 您可以从内置函数中获得的唯一信息是使用subn 而不是sub 执行的替换次数。但是正如您所说,没有功能可以跟踪执行的替换,但是您可以轻松地手动获得与您显示的相同的结果。
    • 谢谢!这正是我一直在寻找的。实际的文本字符串实际上要复杂得多,所以我已经在使用subn 来计算模式实例的数量。我主要关心的不是可读性,而是更多关于重复搜索/替换大量行的运行时间。
    • 感谢您的解决方案。你让我开心。
    【解决方案2】:

    你可以使用这个正则表达式:

    正则表达式:

    \[(.*?)\].*?(\w[\w\s]+\w).*?\[(.*?)\]
    

    Python 代码:

    import re
    
    a = '[fox] dog turtle [cat]'
    pattern = r'\[(.*?)\].*?(\w[\w\s]+\w).*?\[(.*?)\]'
    res = re.search(pattern,a)
    r1,r2,r3 = res.groups()
    

    演示: Here

    【讨论】:

    • 谢谢,但我的实际文本字符串要复杂得多,括号中的单词不能保证存在或以这种方式排序,所以像这样的严格模式不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 2020-11-29
    相关资源
    最近更新 更多