Vin*_*igh 12 java regex string contains
我有一个来自文本区域的String :(带有变量名string
)
This is the first line
And this is the second
Run Code Online (Sandbox Code Playgroud)
如果我将其分成单独的单词使用string.split(" ")
,那么检查哪些单词包含"\n"
for(String s : string.split(" ")) {
if(s.contains("\n"))
System.out.println(s);
}
Run Code Online (Sandbox Code Playgroud)
这两个line
和And
我的句子包含\n
.但是,如果我要检查这个词是以它开头\n
还是以它结尾,它就没有给我任何结果.
if(s.contains("\n")) {
System.out.println("Contains");
if(s.startsWith("\n"))
System.out.println("Starts with");
else if(s.endsWith("\n")) {
System.out.println("Ends with");
else
System.out.println("Does not contain");
}
Run Code Online (Sandbox Code Playgroud)
我的结果是:
Contains
Does not contain
Run Code Online (Sandbox Code Playgroud)
因此,如果单词包含a \n
,但它不以它开头或结尾,那么究竟是什么replaceAll(String, String)
呢?如何在不使用的情况下管理它?
Chr*_*ian 24
会发生什么是字符串看起来像:
"This is the first line\nAnd this is the second"
Run Code Online (Sandbox Code Playgroud)
所以当你分开它时," "
你得到:
"line\nAnd"
Run Code Online (Sandbox Code Playgroud)
当你打印它时,它看起来像两个单独的字符串.为了演示这一点,尝试在for
循环中添加额外的打印:
for (final String s : string.split(" ")) {
if (s.contains("\n")) {
System.out.print(s);
System.out.println(" END");
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
line
And END
Run Code Online (Sandbox Code Playgroud)
当你试图检查一个字符串是否开始或结束时"\n"
你将得不到任何结果,因为事实上字符串"line\nAnd"
不会开始或结束"\n"
是这里 "line\nAnd"
当你打印它时,它出来了
line
And
Run Code Online (Sandbox Code Playgroud)