[英]Is there a simple way to search for a sentence in a text that may contain line separators in Java?
我有这个字符串
String text = "Hello world my " + System.lineSeparator() + "name is Bob";
我也有这句话
String sentence = "world my name is";
我注意到,由于行分隔符,您无法在带有indexOf()
的text
中找到sentence
。 有没有简单快捷的方法可以在多行字符串上找到sentence
?
编辑:我还需要按原样打印找到的字符串,这意味着,如果在我找到sentence
的文本中有System.lineSeparator()
,我需要使用该分隔符将其打印出来。
输入输出示例:
输入:
Hello world my
name is Bob
Output:
world my
name is
谢谢大家的回复!
谢谢@alfasin
text.replaceAll(System.lineSeparator(), "").indexOf(sentence);
String.indexOf()
似乎对我来说工作正常。 这是一个示例。
https://repl.it/repls/ProperAcademicObject
示例中的代码如下:
String sentence = "Sentence";
String text = "This is a test." + System.lineSeparator() + "one two three." + System.lineSeparator() + sentence;
System.out.println(text);
System.out.println(text.indexOf("one two three"));
System.out.println(text.indexOf(sentence));
output如下:
This is a test.
one two three.
Sentence
16
31
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.