【发布时间】: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