代码之家  ›  专栏  ›  技术社区  ›  braveterry

我可以使用哪个Java正则表达式来匹配在查询字符串前面有大写字母的URL?

  •  1
  • braveterry  · 技术社区  · 14 年前

    我正在尝试创建一个正则表达式,该正则表达式与查询字符串前面有大写字母的URL相匹配。我想捕获包含问号的查询字符串,并捕获非查询字符串部分。如果没有查询字符串,但是有一个大写字母,那么应该捕获非查询字符串部分。

    举几个例子:

    /contextroot/page.html?param1=value1&param2=value2 NO MATCH
    /contextroot/page.html?param=VALUE&param2=value2   NO MATCH
    
    /contextroot/Page.html?param=value                 MATCH
    /contextroot/Page.html                             GROUP 1
    ?param=value                                       GROUP 2
    
    /contextroot/page.HTML                             MATCH
    /contextroot/page.HTML                             GROUP 1
    

    ^(.*[A-Z].*)(\??.*)$
    

    它坏了。这永远不会捕获查询字符串。

    2 回复  |  直到 14 年前
        1
  •  2
  •   Tim Pietzcker    14 年前
    ^/contextroot/([^?]*[A-Z][^?]*)(\?.*)?$
    

    ^/contextroot/  # literal start of URL
    (               # match group 1
      [^?]*         # anything except `?` (zero or more)
      [A-Z]         # one capital letter
      [^?]*         # see above
    )
    (               # match group 2
      \?            # one ?
      .*            # anything that follows
    )?              # optionally
    $               # end of string    
    
        2
  •  2
  •   Tomalak    14 年前
    (^/contextroot/(?=[^?A-Z]*[A-Z])[^?]*)(\?.*)?
    

    说明:

    (                 # match group 1
      ^/contextroot/  #   literal start of URL (optional, remove if not needed)
      (?=             #   positive look-ahead...
        [^?A-Z]*      #     anything but a question mark or upper-case letters
        [A-Z]         #     a mandatory upper-case letter
      )               #   end look-ahead
      [^?]*           #   match anything but a question mark
    )                 # end group 1
    (                 # match group 2
      \?.*            #   a question mark and the rest of the query string
    )?                # end group 2, make optional
    

    请注意,这是为了检查一个单一的网址和不工作时,运行一个多行字符串。

    (^/contextroot/(?=[^?A-Z\r\n]*[A-Z])[^?\r\n]*)(\?.*)?