[英]Java doesn't work with regex \s, says: invalid escape sequence
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”替换所有“ß” ...它对于“ß”效果很好,但是以某种方式,eclipse不允许我将\\ 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! 提前致谢!
您需要逃脱斜线
start_from = start_from.replaceAll("\\s", "+");
The problem is that \\
is an escape character in java as well as regex patterns. 问题是
\\
是Java 和正则表达式模式中的转义字符。 If you want to match the regex pattern \\n
, say, and you'd go ahead and write 如果要匹配正则表达式
\\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. 正则表达式模式最终不会成为
\\n
;它将成为实际的换行符,因为这就是Java中的"\\n"
含义。 If you want the pattern to 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. 如果希望模式包含反斜杠,则需要确保转义该反斜杠,以使其在字符串中不被视为特殊字符。
replaceAll("\\s", "+");
You can use the java.util.regex.Pattern class and use something like p = Pattern.compile("\\s");
您可以使用java.util.regex.Pattern类,并使用类似
p = Pattern.compile("\\s");
in combination with p.matcher(start_from).replaceAll("+")
. 与
p.matcher(start_from).replaceAll("+")
。 Alternatively, just escape your "\\s" metacharacter as "\\\\s". 或者,只需将“ \\ s”元字符转义为“ \\\\ s”即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.