【问题标题】:Negative pattern matching Reg ex In PythonPython中的负模式匹配正则表达式
【发布时间】:2016-07-18 11:36:27
【问题描述】:

尝试使用否定前向替换所有不匹配模式的字符串:

regexPattern = '((?!*' + 'word1|word2|word3' + ').)*$'  
mytext= 'jsdjsqd word1dsqsqsword2fjsdjswrod3sqdq'
return re.sub(regexPattern, "P", mytext)

#Expected Correct Output:  'PPPPPPword1PPPPPPword2PPPPPword3PPP'

#BAD Output:  'jsdjsqd word1dsqsqsword2fjsdjswrod3sqdq'

我尝试了这个,但它不起作用(字符串保持不变)。 如何修改它? (认为​​这是相当困难的正则表达式)

【问题讨论】:

  • 发布示例数据以及预期输出。
  • 在'((?!*'中删除*
  • 您要替换所有不包含word1 或word2 或word3 的字符串? r'(?s)^(?!.*(?:word1|word2|word3)).*$'。 效果不好 - 它对你有什么作用,有什么问题?
  • 上面的代码抛出了一个众所周知的nothing to repeat error。
  • 您提交的代码似乎也不起作用。有什么想法吗?

标签: python regex python-3.x regular-language


【解决方案1】:

您可以使用两阶段的方法:首先,将 匹配的字符替换为某个特殊字符,然后将其用作掩码来替换所有 other字符。

>>> text= 'jsdjsqd word1dsqsqsword2fjsdjsword3sqdq'
>>> p = 'word1|word2|word3'
>>> mask = re.sub(p, lambda m: 'X' * len(m.group()), text)
>>> mask
'jsdjsqd XXXXXdsqsqsXXXXXfjsdjsword3sqdq'
>>> ''.join(t if m == 'X' else 'P' for (t, m) in zip(text, mask))
'PPPPPPPPword1PPPPPPword2PPPPPPword3PPPP'

当然,除了X,您可能必须选择一个不同的字符,该字符不会出现在原始字符串中。

【讨论】:

    【解决方案2】:

    你可以使用

    import re
    regex = re.compile(r'(word1|word2|word3)|.', re.S)
    mytext = 'jsdjsqd word1dsqsqsword2fjsdjsword3sqdq'
    print(regex.sub(lambda m: m.group(1) if m.group(1) else "P", mytext))
    // => PPPPPPPPword1PPPPPPword2PPPPPPword3PPPP
    

    见IDEONE demo

    正则表达式是(word1|word2|word3)|.:

    • (word1|word2|word3) - word1,或word2,或word3 字符序列
    • | - 或者...
    • . - 任何字符(包括作为re.S DOTALL 模式的换行符)

    见regex demo

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多