首页 > 解决方案 > 正则表达式 - 如何精确匹配 url 中的 3 个单词?

问题描述

我想从 url 的搜索短语中匹配正则表达式 3 个单词,但不匹配 4 个或更多。URL 可以有一些变化。问题如下图所示。正则表达式应该匹配和不匹配以下示例:

SHOULD MATCH:
https://example.com/search=any%20url%20encoded_word-here
https://example.com/search=any%20url%20encoded_word-here%20
https://example.com/search=z%C5%82oty%20z%C5%82oty%20z%C5%82oty
https://example.com/search=z%C5%82oty%20z%C5%82ota%20%C5%82ata
https://example.com/search=any%20%20word%20%20here
https://example.com/search=any%20word%20here&color=blue
https://example.com/search=any-1st%20word_2nd%20here3

SHOULD NOT MATCH:
https://example.com/search=one%20two%20three%20four
https://example.com/search=one%20%20two%20%20three%20%20four
https://example.com/search=one%20%20two%20three%20%20four
https://example.com/search=one%20%20two%20%20three%20%20four
https://example.com/search=one%20two%20three%20four&color=blue
https://example.com/search=z%C5%82oty%20z%C5%82oty%20z%C5%82oty%20word

从这里开始https://regex101.com/r/0qzCJV/1但我不知道如何不匹配条件。你们能帮帮我吗?

标签: regexregex-negation

解决方案


当有 3 个%20后跟至少 1 个字符时,您可以使用此正则表达式和负前瞻来使匹配失败:

^(?!(?:.+?%20){3}.)(?:.+?%20){2}.+?(?:%20)?$

正则表达式演示

正则表达式详细信息:

  • ^: 开始
  • (?!(?:.+?%20){3}.)%20: 当我们有 3 次出现后跟至少 1 个字符时,负前瞻使匹配失败
  • (?:.+?%20){2}: 匹配 1+ 后跟的任何字符%20。重复此匹配 2 次以匹配 2 个单词
  • .+?: 匹配任何字符的 1+
  • (?:%20)?%20:在结束前匹配可选
  • $: 结尾

或者使用所有格量词来减少回溯:

^(?!(?:.+?%20){3}+.)(?:.+?%20){2}.+?(?:%20)?$

推荐阅读