在WP重定向插件中,正则表达式匹配不以字符串开头的URL


Regex to match URL that does not begin with string in WP Redirection plugin

目前,我在WordPress中使用重定向插件以这种方式重定向所有包含q问号的url:

Source: /(.*)'?(.*)$
Target: /$1

这个效果很好。它将重定向任何带有?的链接,例如/good-friends-are-great.html?param=x/good-friends-are-great.html

但是,现在我需要破例。我需要允许/friends传递GET参数,例如/friends?guest=1&event=chill_out&submit=2/friends/?more_params,而不截断参数。

我已经尝试修改正则表达式在插件:

Source: /(?!friends/?)'?(.*)$
Target: /$1

但这不起作用。使用上面的表达式,任何带有?的链接都不再被重定向。

你能帮忙吗?

您可以使用下面的正则表达式:

/(.*(?<!friends)(?<!friends/))'?.*$

看到演示

正则表达式使用了2次负向后查找,因为在这种正则表达式风格中,我们不能使用可变宽度的向后查找。(.*(?<!friends)(?<!friends/))匹配?之前的任意字符,但检查?之前是否没有friendsfriends/

编辑:

这是我的第一个不适合当前场景的正则表达式:

/((?:(?!friends/?).)+)'?.*$

其子模式(?:(?!friends/?).)+匹配不包含friendsfriends/的字符串

不应该替换第一个(.*),而应该直接添加:

Source: /(?!friends/?)(.*)'?(.*)$
Target: /$1

负正向组(?!friends/?)本身不匹配任何内容;它只是阻止某些匹配。