在正则表达式匹配中不替换换行符?

时间:2014-05-19 00:15:10

标签: java regex

我有以下代码尝试解析以#开头的行并用空字符串替换每一行,但换行符没有被剥离:

- 输入 -

# Remove this.
# remove this
# remove this line
keep # this line
keep this # line too

- 实际输出(。表示空行) -

.   
.
.
keep # this line
keep this # line too

- 预期产出

keep # this line
keep this # line too

- 代码 -

    String text = "# Remove this.\n# remove this\n# remove this line\n" +
        "keep # this line\nkeep this # line too";
    System.out.println(text);
    Pattern PATTERN = Pattern.compile("^#(.*)$", Pattern.MULTILINE);
    Matcher m = PATTERN.matcher(text);
    if (m.find()) {
        text = m.replaceAll("").replaceAll("[\n]+$", "");
        System.out.println(text);
    }

如何删除正则表达式匹配中的\ n?

1 个答案:

答案 0 :(得分:2)

使用^#.*[\n]选择包含换行符的行。