Java 无效的转义序列(有效的是 \b \t \n \f \r \" \' \ )
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16178955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )
提问by Annika
I have a problem with a regex in java.
我在 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
谢谢
采纳答案by Uku Loskit
This should work ^(?:(?:([01]?\\d|2[0-3]):)?([0-5]?\\d):)?([0-5]?\\d)$
这应该工作 ^(?:(?:([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).
原因是错误消息中列出的符号具有特殊含义,但\d
不是用于 using 的那些定义的特殊符号之一\
,这意味着您必须对其进行转义(通过\
在符号前添加额外的符号)。
回答by óscar López
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:
每当您在 Java 中编写正则表达式时,请记住对\
定义正则表达式的字符串中使用的字符进行转义。换句话说,如果您的正则表达式包含一个\
,那么您必须编写两个\\
。例如,您的代码应如下所示:
^(?:(?:([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, \\
.
你为什么问?因为在 Java 的字符串中,\
是用于表示特殊字符(例如:制表符、换行符等)的转义字符,如果字符串包含 ,\
那么它本身必须通过\
在它前面加上另一个来转义。因此,\\
。
For the record, hereis the Java language specification page listing the valid escape characters and their meanings, notice the last one:
作为记录,这里是 Java 语言规范页面,列出了有效的转义字符及其含义,注意最后一个:
\b backspace
\t horizontal tab
\n linefeed
\f form feed
\r carriage return
\" double quote
\' single quote
\ backslash
回答by sfblap
you can use notepad++ with find / and replace with //
您可以将记事本++与 find / 一起使用并替换为 //