【问题标题】:REGEX - how to match exacly 3 words from url?正则表达式 - 如何精确匹配 url 中的 3 个单词?
【发布时间】:2021-05-19 10:25:58
【问题描述】:

我想匹配来自 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 开始,但我不知道如何在条件上不匹配。大家能帮帮我吗?

【问题讨论】:

  • 是什么决定了URL 中的单词边界?换句话说,搜索中单词之间的分隔符是什么?一次我看到%20 和一次&
  • 类似.*/search=(?:(?:(?!%20).)*(?:%20|$)+){3}$?
  • 或者,.*/search=((?:(?!%20).)*)(?:%20)+((?:(?!%20).)*)(?:%20)+((?:(?!%20).)*)(?:%20)*$ (demo)?
  • 单词边界是空格 (%20) - 感谢它现在可以使用 - 救了我的命 :)

标签: regex regex-negation


【解决方案1】:

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

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

RegEx Demo

正则表达式详细信息:

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

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

^(?!(?:.+?%20){3}+.)(?:.+?%20){2}.+?(?:%20)?$
【解决方案2】:

试试这个:

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

live demo

这使用否定前瞻来匹配%20,然后匹配任意数量的%20,然后再匹配两次。然后用任何不是%20 的东西结束,除了结尾可能有 %20。


注意:您的示例不匹配项不包括 小于 3 的网址,例如

https://example.com/search=one%20two

【讨论】:

  • 谢谢,问题是只能得到三个单词的短语,谢谢!
猜你喜欢
  • 2017-09-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
相关资源
最近更新 更多