Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/104.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 模式中任意位置的字符的正则表达式不匹配_Python_Regex - Fatal编程技术网

Python 模式中任意位置的字符的正则表达式不匹配

Python 模式中任意位置的字符的正则表达式不匹配,python,regex,Python,Regex,在Python2.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 但是,如

在Python2.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

您可以使用负前瞻:

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


(?!\d*3)
如果在0+位之后出现
3
则会断言不匹配。

此模式有效吗<代码>[0124-9]{4}我要寻找的是一种与模式不匹配的方法。如果模式中的某个特定字符,我不会寻找专门消除3s的方法。1234只是一个例子。我不知道是否有一个特定的“如果这个字符不存在”正则表达式模式。您需要针对您所处的任何情况对其进行自定义。这取决于实际的预期输入,但使用求反字符集可能是最简单的方法,例如
[^a-z\s3]{4}
使用回调函数,如
re.sub(r“(\d{4})”,lambda x:x.group()如果x.group()中的“3”,否则“[my number]”,s)