How do I express “:” but not preceded by “\” in a Java regular expression?

后端 未结 2 2003
情深已故
情深已故 2021-01-05 05:17

How can I express \"not preceded by\" in a Java regular expression? For example I would like to search for \":\" but only when it is not directly preceded by \"\\\". How c

2条回答
  •  别那么骄傲
    2021-01-05 05:59

    Use a negative lookbehind:

    "(?

    The reason for the four backslashes is:

    • the backslash is a special character in regular expressions so you need the regular expression \\ to match a single backslash.
    • backslashes must be escaped in Java strings, so each of the above backslashes must be written as \\, giving a total of four.

    Example code:

    Pattern pattern = Pattern.compile("(?

    Output:

    10
    

提交回复
热议问题