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

I have a problem with regex in java.

When I try to use this regex:

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

I get the following error

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

I do not know how to deal with this error. I already tried to double the backslash, but that didn't work. Hope someone can help me.

thanks

+8
java regex
source share
3 answers

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

The reason is that the listed characters in the error message have special meaning, but \d not one of those specific special characters for using \ , which means you need to avoid it (by adding an extra \ in front of the character).

+10
source share

Whenever you write regular expressions in Java, remember to avoid the \ characters used in the line that defines the regular expression. In other words, if your regular expression contains one \ , you should 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 strings \ is an escape character used to denote special characters (example: tabs, new lines, etc.), and if the string contains \ , then it itself must be escaped by adding another \ in front of it. Therefore, \\ .

For the record here , this is the Java language specification page that lists valid escape characters and their meanings, note the last:

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

you can use notepad ++ with find / and replace with //

+1
source share

All Articles