我需要一个正则表达式能够匹配除以特定模式开头的字符串以外的所有内容(特别是index.php和后面的内容,如index.php?id=2342343)。


当前回答

在Python中:

>>> import re
>>> p='^(?!index\.php\?[0-9]+).*$'
>>> s1='index.php?12345'
>>> re.match(p,s1)
>>> s2='index.html?12345'
>>> re.match(p,s2)
<_sre.SRE_Match object at 0xb7d65fa8>

其他回答

您可以从一开始就使用负向前,例如,^(?!foo)。*$不应该匹配以foo开头的任何内容。

在Python中:

>>> import re
>>> p='^(?!index\.php\?[0-9]+).*$'
>>> s1='index.php?12345'
>>> re.match(p,s1)
>>> s2='index.html?12345'
>>> re.match(p,s2)
<_sre.SRE_Match object at 0xb7d65fa8>

经过长时间的搜索,我发现了这条线索。我在多次搜索和替换某些事件时遇到了这个问题。但我用的模式一直匹配到最后。在下面的例子

import re

text = "start![image]xxx(xx.png) yyy xx![image]xxx(xxx.png) end"
replaced_text = re.sub(r'!\[image\](.*)\(.*\.png\)', '*', text)
print(replaced_text)

gave

start* end

基本上,正则表达式从第一个![图像]匹配到最后一个。png,吞没了中间的yyy

使用Firish在https://stackoverflow.com/a/17761124/429476上面发布的方法来打破事件之间的匹配。这里的空间不匹配;因为单词是用空格隔开的。

replaced_text = re.sub(r'!\[image\]([^ ]*)\([^ ]*\.png\)', '*', text)

得到了我想要的

start* yyy xx* end

你可以在字符集的开头加上^来匹配除这些字符以外的任何字符。

[^=]*

将匹配除=

只需匹配/^index\.php/,然后拒绝匹配它的任何东西。