gpt4 book ai didi

java - 为什么 Java 中的正则表达式无法将 s 识别为空格字符?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:51:17 25 4
gpt4 key购买 nike

我看了很多网页(例如:http://www.wellho.net/regex/java.html),他们都提到\s可以代表任何空格字符。但是当我在 Java 中使用\s 时,它不是一个合格的表达式。

有人知道原因吗?

最佳答案

字符串中的反斜杠需要被引用才能工作。

例如,以下工作正常:

public class testprog {
public static void main(String args[]) {
String s = "Hello there";
System.out.println (s.matches(".*\\s.*"));
}
}

输出:

true

如果你使用像 "\s" 这样的字符串,你应该会得到如下错误:

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

来自您的编译器,因为 \s 不是有效的转义序列(对于字符串,我的意思是,不是正则表达式)。

关于java - 为什么 Java 中的正则表达式无法将 s 识别为空格字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3518112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com