在正则表达式中组合规则

huangapple go评论55阅读模式
英文:

Combinging rules in Regex

问题

尝试编写一个用于WP重定向的规则

我有规则^((?!json).)*$

该规则忽略:

  • /wp-json/aber

和规则^([^.\?]*[^\/])$

该规则忽略:

  • /aber.css
  • /france?foobar=1

但我似乎无法弄清楚如何将它们合并为一个单一的规则,以忽略所有三个。如果我添加 [^.?|json],则会排除包含这些字符中的任何一个的任何URL。它只需要在URL中的任何位置精确地是“json”或包含.或?的URL。

示例:

不匹配:

  • /wp-json/aberdeen
  • /aberdeen.css
  • /aberdeen?foobar=1

匹配:

  • /wp-jsn/aberdeen
  • /aberdeen
英文:

Trying to write a rule for a WP redirect

I've got the rule ^((?!json).)*$

Which ignores:

  • /wp-json/aber

And the rule ^([^.\?]*[^\/])$

Which ignores:

  • /aber.css
  • /france?foobar=1

But I can't seem to figure out how t combine them into a single rule that ignores all three. if I add [^.?|json] if rules out any URLs including any of those characters individually. It only needs to be exactly "json" located anywhere in the URL or URLs that include a . or a ?

Examples:

Dont match:

  • /wp-json/aberdeen
  • /aberdeen.css
  • /aberdeen?foobar=1

Match:

  • /wp-jsn/aberdeen
  • /aberdeen

答案1

得分: 2

第一个模式 ^((?!json).)*$ 简单地断言输入中没有出现 json。我们可以通过在第二个模式中添加负向先行断言来重构,以排除 json

^(?!.*json)([^.\?]*[^\/])$
英文:

Well the first pattern ^((?!json).)*$ simply asserts that json does not appear anywhere in the input. We can refactor the second pattern by adding a negative lookahead to rule out json:

^(?!.*json)([^.\?]*[^\/])$

huangapple
  • 本文由 发表于 2023年2月8日 22:09:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75386974.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定