regex - 正则表达式 - 如何精确匹配 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但我不知道如何不匹配条件。你们能帮帮我吗?
解决方案
当有 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)?$
推荐阅读
- python - google colab 导入外部文件时出错
- c# - 如何在 Cofoundry 的显示页面上重用 SelectList 编辑器
- python - 在函数中创建 pandas DataFrame
- arrays - 数组中的 Swift 分组顺序对象
- docker - 无法访问 docker 网络服务,但可以从外部 IP 访问
- github - 添加新存储库时的Github问题
- pandas - 合并 groupby ffill 然后 bfill 的代码
- c++ - C ++共享内存并从另一个可执行文件调用一个可执行文件中的函数?
- azure - http:来自 10.244.0.6:36004 的 TLS 握手错误:远程错误:tls:证书错误
- wordpress - 如何在 Wordpress 中上传时自动将照片从小调整为大?