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

匿名 (未验证) 提交于 2019-12-03 01:07:01

问题:

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 get the following error

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

I don't know how to handle that error. I already tried to double the backslashes, but it didn't work. I hope someone can help me with this.

Thanks

回答1:

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

The reason is that the listed symbols in the error message have special meaning, but \d is not one of those defined special symbols for using \, this means you have to escape it (by adding an extra \ in front of the symbol).



回答2:

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 


回答3:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!