如果字符在模式中的任何地方的正则表达式不匹配

时间:2017-11-17 19:28:20

标签: python regex

在python 2.7中使用正则表达式。

我希望匹配字符串中的模式,除非模式中的任何位置存在某个字符。说一些像

这样简单的东西
>>>import re
>>>string = "hello this is a number 1234 and goodbye"
>>>re.sub("(\d{4})", "[my number]")

哪会返回

hello this is a number [my number] and goodbye

但是,如果数字3出现在模式内的任何位置,而不是整个字符串,我想得到不匹配。我该怎么做?

所以这不匹配。

>>>"hello this is a number 1234 and goodbye"
hello this is a number 1234 and goodbye

但这些确实

>>>"hello this is a number 31245 and goodbye"
>>>"hello 3 this is a number 1245 and goodbye"
hello this is a number 3[my number] and goodbye
hello 3 this is a number [my number] and goodbye

1 个答案:

答案 0 :(得分:1)

您可以使用否定前瞻:

re.sub(r'(?!\d*3)\d{4}', "[my number]", str)

RegEx Demo

如果在0+位数后面有(?!\d*3),则

3会声明不匹配。