我有一个代码,用于查找正则表达式匹配,并在正则表达式匹配后添加一个新行。这可以在第一次单击按钮时起作用,但是当我再次单击它时,它仍然会捕获正则表达式。
示例场景:
更改以'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.
我很困惑为什么在第二次点击时,它没有注意到没有更多的'狗'实例。没有换行。
提前感谢您的帮助!
答案 0 :(得分: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");
答案 1 :(得分: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。