Java regex: Negative lookahead

后端 未结 1 573
轻奢々
轻奢々 2020-12-18 18:34

I\'m trying to craft two regular expressions that will match URIs. These URIs are of the format: /foo/someVariableData and /foo/someVariableData/bar/someO

相关标签:
1条回答
  • 2020-12-18 19:01

    Try

    String regex = "/foo/(?!.*bar).+";
    

    or possibly

    String regex = "/foo/(?!.*\\bbar\\b).+";
    

    to avoid failures on paths like /foo/baz/crowbars which I assume you do want that regex to match.

    Explanation: (without the double backslashes required by Java strings)

    /foo/ # Match "/foo/"
    (?!   # Assert that it's impossible to match the following regex here:
     .*   #   any number of characters
     \b   #   followed by a word boundary
     bar  #   followed by "bar"
     \b   #   followed by a word boundary.
    )     # End of lookahead assertion
    .+    # Match one or more characters
    

    \b, the "word boundary anchor", matches the empty space between an alphanumeric character and a non-alphanumeric character (or between the start/end of the string and an alnum character). Therefore, it matches before the b or after the r in "bar", but it fails to match between w and b in "crowbar".

    Protip: Take a look at http://www.regular-expressions.info - a great regex tutorial.

    0 讨论(0)
提交回复
热议问题