正则表达式以匹配具有或不具有尾随段的URL

时间:2015-01-08 22:48:40

标签: regex

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

/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个段w /可选查询字符串和尾随正斜杠。上面示例中的cflynn07101以及testing段是动态的。 reposconstants是一致的。

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

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

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

修改 regexr分享:http://www.regexr.com/3a6f4

1 个答案:

答案 0 :(得分:2)

没有组成的选项:

(?:[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