2012-03-27 57 views
1

我试图'环绕'搜索,基本上忽略\ n当使用ether indexOf或正则表达式模式时。我不能只删除所有换行符,因为那些索引发现是错误的。忽略在干草堆中找到换行符的换行符并保留文本位置

例如:

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函数,并试图创建一个'wrap around'选项。 任何想法?

+1

你是什么意思忽略它们?你说你不能删除它们,因为索引是错误的,但是如果你做indexOf它会计算换行符,并且你不会忽略它们。请显示所需的输入和输出。 – Danny 2012-03-27 18:05:59

+1

此外,请显示您正在尝试的内容(通过代码),以便人们可以尝试引导您进入解决方案。 – 2012-03-27 18:13:53

回答

2

你需要采取搜索关键字,并通过你的哎堆栈在进行搜索之前,每一个字符后插嘴可选换行做准备。考虑以下代码:

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"); 

OUTPUT:

Start: 4 End: 8 

BTW您的预期输出5,9似乎不正确的给我。

+0

对于简单的字符串看起来不错,但更复杂的正则表达式搜索呢?对不起,代码中有一个输入错误 – RedHatter 2012-03-27 20:40:42

+0

请提供一些“更复杂的正则表达式搜索”的例子。据我了解,你正试图通过忽略中间的换行符(至少这是问题标题所说的)来在干草堆中找到针。 – anubhava 2012-03-27 20:44:26

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

试试这个

+0

这将**替换**换行符,完全从字符串中删除它们。这样做会扰乱索引。 – RedHatter 2012-03-27 19:20:09