【问题标题】:Regular expression to match url with or without trailing segment正则表达式匹配带有或不带有尾段的 url
【发布时间】:2015-01-09 07:07:55
【问题描述】:

尝试构建正则表达式以匹配以下 url 模式:

/repos/cflynn07/101/contents/testing /repos/cflynn07/101/contents/testing?foo=bar /repos/cflynn07/101/contents/testing/ /repos/cflynn07/101/contents/testing/?foo=bar /repos/cflynn07/101/contents /repos/cflynn07/101/contents?foo=bar /repos/cflynn07/101/contents/ /repos/cflynn07/101/contents/?foo=bar

基本上是一个 url,它可以有 4 或 5 个片段,带有可选的查询字符串和尾部正斜杠。上面示例中的 cflynn07101testing 段是动态的。 reposconstants 是一致的。

到目前为止,我有:
^\/repos\/[A-z0-9]+\/[A-z0-9]+\/contents\/[A-z0-9]+?\/?\??.+

我最难理解的部分是:
[A-z0-9]+?(第三个字符集匹配正则表达式组件)。

如何在正则表达式中设置可选的匹配字符集?谢谢!

编辑 正则表达式分享:http://www.regexr.com/3a6f4

【问题讨论】:

标签: regex


【解决方案1】:

不分组的可选性:

(?:[A-z0-9]+)?

但你所需要的只是:

^\/(?:(?:[a-zA-Z0-9]+\/){3,5})?(?:[^\/]+)?$

解释:

^                               #start
    \/                          # "/"
    (?:                         #not a group
        (?:                     #not a group
           [a-zA-Z0-9]+\/       #letters, numbers and than symbol "/" 
        ){3,5}                  #3-5 occurrences 
    )?                          #not necessary 
    (?:                         #not a group
        [^\/]+                  #everything but not a symbol "/"
    )?                          #not necessary
$                               #end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多