Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )

后端 未结 3 1884
旧时难觅i
旧时难觅i 2020-12-06 11:41

I have a problem with a regex in java.

When I try to use this regex:

 ^(?:(?:([01]?\\d|2[0-3]):)?([0-5]?\\d):)?([0-5]?\\d)$  

I g

3条回答
  •  抹茶落季
    2020-12-06 12:30

    Whenever you're writing regular expressions in Java, remember to escape the \ characters used in the string that defines the regular expression. In other words, if your regular expression contains one \, then you HAVE to write two \\. For example, your code should look like this:

    ^(?:(?:([01]?\\d|2[0-3]):)?([0-5]?\\d):)?([0-5]?\\d)$  
    

    Why, you ask? because in Java's strings, \ is the escape character used to denote special characters (example: tabs, new lines, etc.) and if a string contains a \ then it must itself be escaped, by prepending another \ in front of it. Hence, \\.

    For the record, here is the Java language specification page listing the valid escape characters and their meanings, notice the last one:

    \b  backspace
    \t  horizontal tab
    \n  linefeed
    \f  form feed
    \r  carriage return
    \"  double quote
    \'  single quote
    \\  backslash
    

提交回复
热议问题