2016-06-13 85 views
2

我有一个代码,查找正则表达式匹配,并在正则表达式匹配后添加一个新行。这可以在第一次点击按钮时起作用,但是当我再次单击它时,它仍然会捕获正则表达式。Java正则表达式匹配:负面看起来不工作

示例场景:

变化与结尾的所有句子 '的狗。'并添加一个新行,如果它不是该行的结尾。鼠标点击事件里面

示例代码:

Pattern pattern = Pattern.compile("dog\\.(?!\n)"); 
Matcher matcher = pattern.matcher(paragraph); 
paragraph = matcher.replaceAll("dog\\.\n"); 

样品输入:

我发现了一个街头的动物。这是一只狗。然后,狗找到另一只狗。看到两只狗互相吠叫,真是有趣。

按钮,首先点击实现代码:

I found a street animal. It was a dog. 
Then the dog found another dog. 
It was kind of fun to see the two dogs barking to each other. 

按钮的第二次点击实现代码:

I found a street animal. It was a dog. 

Then the dog found another dog. 

It was kind of fun to see the two dogs barking to each other. 

我为什么在第二次点击,就没有注意到很困惑没有更多的“狗”。没有新的路线。

在此先感谢您的帮助!

+1

使用Pattern Pattern = Pattern.compile(“dog \\。(?!\\ n)”);' – anubhava

+0

嗨@anubhava,我试过了,但结果仍然一样。 –

+0

也许'(?!\\ r \\ n)'工作,如果文件使用CRLF –

回答

1

您可以使用:

String str = 
"I found a street animal. It was a dog. \nThen the dog found another dog. \nIt was kind of fun to see the two dogs barking to each other."; 

Pattern pattern = Pattern.compile("(?<=dog\\.(?!\\s*\\n))\\s*"); 
Matcher matcher = pattern.matcher(str); 
str = matcher.replaceAll("\r\n"); 

RegEx Demo

Code Demo

+0

嗨,这段代码有效。但是,一旦我改变输入字符串,它就不起作用。请注意,我正在使用SWT,并且我有一个文本框,用户可以在其中输入执行检查的段落和按钮。 例如: 我输入了示例文本。点击按钮,它会工作,但是当我向第一个文本添加新行并再次单击该按钮时,它不起作用,并删除新添加的文本中的所有空格。 –

+0

嗨,是的,如果它只运行一次,它会工作。我有SWT Window Builder,我可以在运行期间随时更改文本。我有一个用户可以输入文本的文本框。如果用户输入文本并单击该按钮,它将起作用,但是当用户在texbox中添加更多文本并单击该按钮时,它不再起作用。 –

+0

嗨@anubhava,我已经检查,并且它在我在控制台中打印结果时正常工作,但它在SWT文本框中未正确显示。谢谢。 –

0

希望下面的代码可以帮助你..

String paragraph = "I found a street animal. It was a dog. Then the dog found another dog. It was kind of fun to see the two dogs barking to each other."; 
    paragraph = paragraph.replaceAll("dog\\.(?!\n)", "dog\\.\n"); 

日Thnx。

+0

你的解决方案是从匹配的'replaceAll()'方法切换到String的'replaceAll()'方法?这有什么帮助? –

+0

它减少了实现这一点的代码行。 –

+0

但这是*所有*它。你的建议与OP已经做的完全一样,只有一行而不是三行。答案应该试图解决问题中提出的问题,而这个问题不会。 –