【问题标题】:Regular expression to match specific number of characters on url匹配 url 上特定字符数的正则表达式
【发布时间】:2023-01-12 03:57:16
【问题描述】:

我可以制作一个对特定数量的字符返回 true 的正则表达式吗?

我需要的是一个规则来过滤 Google Analytics 上的一些 url,这些 slug 上总是有 5 个字符,删除任何查询字符串。

https://example.com/abcde -> true
https://example.com/abcde/ -> true
https://example.com/abcde?utm_source=google -> true
https://example.com/abcd -> false
https://example.com/abcdef -> false

我尝试使用 regex101.com 构建它但没有成功

【问题讨论】:

  • 是的,你试过什么了吗?也许 /[^?]{5,}([?]?.*)$ regex101.com/r/Bj5yjG/1 假设协议不包括在内
  • https?:\/\/.*\/[[:alpha:]]{5}([^[:alpha:]]|$) 呢?

标签: regex google-analytics


【解决方案1】:

尝试:

https?://.*/[^?/#]{5}(?=/|?|#|$)

Regex demo.


  • https?:// - 匹配 http:// 或 https://

  • .*/-匹配域名+/(贪心)

  • [^?/#]{5} - 完全匹配 5 个非 - ?/#// 字符

  • (?=/|?|#|$) - 字符必须以 /?# 或字符串结尾结尾

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2019-01-04
    • 1970-01-01
    相关资源
    最近更新 更多