首页 > 解决方案 > 正则表达式忽略换行后的结果

问题描述

我需要在使用正则表达式的文本中重复多次的单词之前添加下划线。

所以我现在拥有的是:

    (\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);
}

因此,它在一行的跨度上工作得非常好,并且正则表达式只有在它们在该确切行上重复时才找到单词,然后它才会在其他行上标记该单词。但是如果两个词在两条不同的行上重复,它就会忽略它们。我不知道为什么会发生这种情况,我需要帮助......提前谢谢你!

标签: java

解决方案


您的问题不是因为换行符;这是因为您的正则表达式仅匹配紧邻出现的单词,两次出现之间只有空格。

正则表达式\b([a-zA-Z]+)\b(?=.*\b\1\b)会做你想做的事,因为它.*允许任何文本出现在单词的两次出现之间。也就是说,换行符确实很重要,因为默认情况下.匹配换行符以外的任何字符;所以你需要写Pattern.compile(regex, Pattern.DOTALL)才能让它按你的意愿工作。


推荐阅读