正则表达式排除以/(es | fr | it)/?开头的域路径

时间:2012-07-17 19:53:15

标签: regex url regex-negation

尝试提供与不以国家/地区前缀开头的uri路径匹配的正则表达式。以下用例是一个例子:

'^/$'          == true
'^/es$'        == false
'^/es/$'       == false
'^/es/.*$'     == false
'^/escro.*$'   == true
'^/lies$'      == true # newish
'^/lies/$'     == true # newish
'^/fr$'        == false
'^/fr/$'       == false
'^/fr/.*$'     == false
'^/freedom/$'  == true
'^/it$'        == false
'^/it/$'       == false
'^/it/.*$'     == false
'^/item/.*$'   == true
'^/foo/bar/$'  == true

摘要:应匹配任何未通过“^ /(fr | it | es)$”或“^ /(fr | it | es)/.*$”的网址

1 个答案:

答案 0 :(得分:2)

这是一个更紧凑的版本,对我有用:

^/[^/]*(?<!/(?:es|fr|it))(?:/.*?)?$

我使用PHP引导程序来测试它,you can see from the demo它通过了所有测试用例。

<强>正则表达式:

^               - Start of string
/               - Match a forward slash
[^/]*           - Match anything that's not a forward slash, 0 or more times
(?<!            - Negative lookbehind making sure
  /(?:es|fr|it) -      We didn't match a forward slash followed by (es|fr|it)
)   
(?:/.*?)?       - Match a forward slash followed by any number of characters, optionally
$               - End of string