Java 忽略换行符以在草堆中找到一根针,并保留文本位置

Java 忽略换行符以在草堆中找到一根针,并保留文本位置,java,regex,indexof,Java,Regex,Indexof,我试图“环绕”搜索,在使用ether indexOf或regex模式时基本上忽略\n。我不能删除所有的换行符,因为这样会发现索引错误 例如: Matcher matcher = Pattern.compile("dog").matcher("cat\n do\ng cow"); matcher.find(); int start = matcher.start(); int end = matcher.end(); System.out.println("Start: "+start+" End

我试图“环绕”搜索,在使用ether indexOf或regex模式时基本上忽略\n。我不能删除所有的换行符,因为这样会发现索引错误

例如:

Matcher matcher = Pattern.compile("dog").matcher("cat\n do\ng cow");
matcher.find();
int start = matcher.start();
int end = matcher.end();
System.out.println("Start: "+start+" End: "+end);
应输出:

Start: 5 End: 9 
如果我删除换行符

Matcher matcher = Pattern.compile("dog").matcher("cat\n do\ng cow".replaceAll("\n",""));
那么索引就会被弄乱:

Start: 4 End: 7
注意:我还将使用比示例中更复杂的正则表达式

我正在文本编辑器中实现find函数,并尝试创建一个“环绕”选项。 有什么想法吗

myString.replaceAll("\n","");

试试这个

在搜索hey堆栈之前,您需要获取搜索关键字,并在每个字符后插入可选换行符来准备它。考虑这个代码:

String needle = "dog";
String regex = needle.replaceAll("(.(?!$))", "$1\n?"); // inserts line breaks
// regex now becomes "d\n?o\n?g"
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher("cat do\ng cow");
if (matcher.find()) {
    int start = matcher.start();
    int end = matcher.end();
    System.out.println("Start: "+start+" End: "+end);
}
else
    System.err.println("No match available");
输出:

Start: 4 End: 8

顺便说一句,我觉得您预期的输出5和9不正确。

忽略它们是什么意思?你说你不能删除它们,因为索引是错误的,但是如果你做indexOf,它会计算换行符,你不会忽略它们。请显示所需的输入和输出。此外,请显示您正在尝试的内容(通过代码),以便人们可以尝试引导您进入解决方案。这将替换换行符,完全从字符串中删除它们。这样做会弄乱索引。对于简单字符串看起来不错,但是对于更复杂的正则表达式搜索呢?抱歉,代码中有输入错误。请提供一些
更复杂的正则表达式搜索的示例。据我所知,你试图通过忽略中间的换行字符(至少问题标题是这样说的)来大海捞针。