Regex for matching a string literal in Java?

前端 未结 1 1674
温柔的废话
温柔的废话 2020-12-19 20:30

I have an array of regular expressions strings. One of them must match any strings found in a given java file.

This is the regex string I have so far: \"(\\\")

相关标签:
1条回答
  • 2020-12-19 21:07

    In Java you can use this regex to match all escaped quotes between " and ":

    boolean valid = input.matches("\"[^\"\\\\]*(\\\\.[^\"\\\\]*)*\"");
    

    Regex being used is:

    ^"[^"\\]*(\\.[^"\\]*)*"$
    

    Breakup:

    ^             # line start
    "             # match literal "
    [^"\\]*       # match 0 or more of any char that is not " and \
    (             # start a group
       \\         # match a backslash \
       .          # match any character after \
       [^"\\]*    # match 0 or more of any char that is not " and \
    )*            # group end, and * makes it possible to match 0 or more occurrances
    "             # match literal "
    $             # line end
    

    RegEx Demo

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