Java正则表达式匹配器:负环顾无效

Java正则表达式匹配器:负环顾无效,java,regex,Java,Regex,我有一个查找正则表达式匹配项的代码,并在正则表达式匹配项后添加一个新行。这在第一次单击按钮时起作用,但当我再次单击它时,它仍然捕获正则表达式 示例场景: 更改所有以“dog”结尾的句子。如果不是该行的结尾,则添加新行 鼠标单击事件中的示例代码: Pattern pattern = Pattern.compile("dog\\.(?!\n)"); Matcher matcher = pattern.matcher(paragraph); paragraph = matcher.replaceAll

我有一个查找正则表达式匹配项的代码,并在正则表达式匹配项后添加一个新行。这在第一次单击按钮时起作用,但当我再次单击它时,它仍然捕获正则表达式

示例场景:

更改所有以“dog”结尾的句子。如果不是该行的结尾,则添加新行

鼠标单击事件中的示例代码:

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.
第二次单击实现代码的按钮:

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.
我很困惑,为什么在第二次点击时,它没有注意到没有新行的“dog”实例

提前感谢您的帮助

您可以使用:

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");
String str=
“我发现了一只街头动物。它是一只狗。\n然后那只狗又找到了另一只狗。\n看到这两只狗互相吠叫真有趣。”;

Pattern=Pattern.compile(“(?希望下面的代码可以帮助您.)

    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.

使用
Pattern=Pattern.compile(“dog\\.(?!\\n)”);
Hi@anubhava,我试过了,但结果还是一样。如果文件使用CRLF@SebastianProske您好,文本仅在运行时通过SWT(窗口生成器)输入textbox。我已经尝试了使用字符串的代码,它可以正常工作(在Windows上)。您的操作系统是什么?MacOS?可能SWT会将您的
\n
转换为
\r
。然后此模式应该可以工作
dog\。(?![\\n\\r])
Hi,这段代码有效。但是,一旦我更改了输入字符串,它就不起作用了。请注意,我正在使用SWT,我有一个文本框,用户可以在其中输入段落和进行检查的按钮。例如:我输入了示例文本。单击了按钮,它就起作用了,但当我在第一个文本中添加新行并再次单击按钮时n、 它不起作用,并且会删除新添加文本中的所有空格。您好,如果它只运行一次,它会起作用。我有SWT Window Builder,可以在运行时随时更改文本。我有一个文本框,用户可以在其中输入文本。如果用户输入文本并单击按钮,它会起作用,但当用户在文本框中添加更多文本并单击t时,它会起作用他按下按钮,它不再工作了。嗨@anubhava,我已经检查过了,当我在控制台打印结果时,它工作正常,但在SWT文本框中没有正确显示。谢谢。嗨@anubhava,我发现了。SWT的新行是\r\n。这就是为什么它只工作一次。谢谢!你的解决方案是从Matcher的
replaceAll()切换
method to String的
replaceAll()
method?这有什么帮助?但仅此而已。您的建议与OP已经在做的完全相同,只是一行而不是三行。答案应该尝试解决问题中提出的问题,而这一行没有。