Python中的负模式匹配Reg-ex

2024-06-16 13:50:39 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试使用负正向替换所有与模式不匹配的字符串:

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

#Expected Correct Output:  'PPPPPPword1PPPPPPword2PPPPPword3PPP'

#BAD Output:  'jsdjsqd word1dsqsqsword2fjsdjswrod3sqdq'

我试过这个,但不起作用(字符串保持不变)。 如何修改?(认为这是相当困难的regex)


Tags: 字符串reoutputreturn模式expectedcorrectword1
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

regex是(word1|word2|word3)|.

  • (word1|word2|word3)-要么是word1,要么是{},或者是{}字符序列
  • |-或者。。。在
  • .-任何字符(包括换行符re.SDOTALL模式已打开)

参见regex demo

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

>>> 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之外,您可能需要选择一个在原始字符串中没有出现的不同字符。在

相关问题 更多 >