java - 正则表达式忽略换行后的结果
问题描述
我需要在使用正则表达式的文本中重复多次的单词之前添加下划线。
所以我现在拥有的是:
(\b[a-zA-Z]+)(?=\s+\1)
示例字符串是:
This is a test test
And this is also a test
And these are also working working tests
预期结果是:
This _is _a _test _test
_And this _is _also _a _test
_And these are _also _working _working tests
但我得到:
This is a _test _test
And this is also a _test
And these are also _working _working tests
Java代码:
public static void main(String[] args) {
String input = "This is a test test\n" +
"And this is also a test\n" +
"And these are also working working tests\n";
String regex = "(\\b[a-zA-Z]+)(?=\\s+\\1)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
while (m.find()) {
input = input.replaceAll("\\b"+m.group(0)+"\\b", "_" + m.group(0));
}
System.out.println(input);
}
因此,它在一行的跨度上工作得非常好,并且正则表达式只有在它们在该确切行上重复时才找到单词,然后它才会在其他行上标记该单词。但是如果两个词在两条不同的行上重复,它就会忽略它们。我不知道为什么会发生这种情况,我需要帮助......提前谢谢你!
解决方案
您的问题不是因为换行符;这是因为您的正则表达式仅匹配紧邻出现的单词,两次出现之间只有空格。
正则表达式\b([a-zA-Z]+)\b(?=.*\b\1\b)
会做你想做的事,因为它.*
允许任何文本出现在单词的两次出现之间。也就是说,换行符确实很重要,因为默认情况下.
匹配除换行符以外的任何字符;所以你需要写Pattern.compile(regex, Pattern.DOTALL)
才能让它按你的意愿工作。
推荐阅读
- ruby-on-rails - 在会话控制器在 Rails 中销毁它之后,为什么 current_account 不为零?
- php - 即使指定了列名,点燃的数据表也会选择所有列
- nativescript - radlistview 不适用于 nativescript 6.3.0
- python - 如何将此 forloop 转换为 pandas lambda 函数,以提高速度
- javascript - 无法在 Google 地图中绘制多边形
- rxjs - 在表单提交时重置/重新启动 Rxjs 流
- bash - sed + 替换特定语法后的内容
- python - 如何使用 python 为下表创建条形图。我通过做一个数据透视然后在 excel 中绘图来创建。(附加所需的输出)
- python - 在数据帧上执行验证(表达式)
- git - Git 添加语法,推送到远程仓库的问题