Java 不适用于正则表达式 \s,说:无效的转义序列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2733255/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:15:08  来源:igfitidea点击:

Java doesn't work with regex \s, says: invalid escape sequence

javaandroidregexwhitespace

提问by MJB

I want to replace all whitespace characters in a string with a "+" and all "?" with "ss"... it works well for "?", but somehow eclipse won't let me use \s for a whitespace.. I tried "\t" instead, but it doesn't work either.. I get the following error:

我想用“+”和所有“?”替换字符串中的所有空白字符 使用“ss”......它适用于“?”,但不知何故日食不会让我使用\ s作为空格......我尝试使用“\ t”代替,但它也不起作用......我明白了以下错误:

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

无效的转义序列(有效的是 \b \t \n \f \r \" \' \ )

this is my code:

这是我的代码:

try {
    String temp1 = from.getText().toString();
    start_from  = temp1.replaceAll("?", "ss");
    start_from  = start_from.replaceAll("\s", "+");
}

why doesn't it work? is it a problem with android, eclipse or what?

为什么不起作用?这是android,eclipse还是什么的问题?

thanks in advance!

提前致谢!

采纳答案by Rob Di Marco

You need to escape the slash

你需要逃避斜线

start_from  = start_from.replaceAll("\s", "+");

回答by dxh

The problem is that \is an escape character in java as well asregex patterns. If you want to match the regex pattern \n, say, and you'd go ahead and write

问题是这\是 java 中的转义字符以及正则表达式模式。如果你想匹配正则表达式模式\n,比如说,你会继续写

replaceAll("\n", "+");

The regex pattern would not end up being \n: it would en up being an actual newline, since that's what "\n"means in Java. If you want the patternto contain a backslash, you'll need to make sure you escape that backslash, so that it is not treated as a special character within the string.

正则表达式模式最终不会是\n:它最终会成为一个实际的换行符,因为这就是"\n"Java中的意思。如果您希望模式包含反斜杠,则需要确保对该反斜杠进行转义,以便它不会被视为字符串中的特殊字符。

replaceAll("\s", "+");

回答by Dustin

You can use the java.util.regex.Pattern class and use something like p = Pattern.compile("\s");in combination with p.matcher(start_from).replaceAll("+"). Alternatively, just escape your "\s" metacharacter as "\\s".

您可以使用 java.util.regex.Pattern 类并将类似的东西p = Pattern.compile("\s");p.matcher(start_from).replaceAll("+"). 或者,只需将您的“\s”元字符转义为“\\s”。