替换包含正则表达式的行

4
我有一个包含多行的输入字符串(由 \n 分隔)。我需要在这些行中搜索一个模式,如果找到,则用空字符串替换整行。
我的代码如下:
Pattern p = Pattern.compile("^.*@@.*$");  
String regex = "This is the first line \n" +  
               "And this is second line\n" +  
               "Thus is @@{xyz} should not appear \n" +  
               "This is 3rd line and should come\n" +  
               "This will not appear @@{abc}\n" +  
               "But this will appear\n";  
Matcher m = p.matcher(regex);  
System.out.println("Output: "+m.group());  

我期待的回应是:
Output: This is the first line       
        And this is second line  
        This is 3rd line and should come  
        But this will appear.

我无法理解它,请帮帮我。
谢谢, Amit
4个回答

5
为了让符号^匹配一行的开头,$匹配一行的结尾,你需要启用多行选项。您可以通过在正则表达式前面添加(?m)来实现这一点,例如:"(?m)^.*@@.*$"
此外,当您的正则表达式找到匹配项时,您希望保留分组,可以像这样完成:
while(m.find()) {
  System.out.println("Output: "+m.group());
}

请注意,正则表达式将匹配这些行(而不是您指定的行):
Thus is @@{xyz} should not appear 
This will not appear @@{abc}

但是,如果您想替换包含@@的行,就像您的帖子标题所示,可以按照以下方式进行:

public class Main { 
    public static void main(String[] args) {
        String text = "This is the first line \n" +  
                      "And this is second line\n" +  
                      "Thus is @@{xyz} should not appear \n" +  
                      "This is 3rd line and should come\n" +  
                      "This will not appear @@{abc}\n" +  
                      "But this will appear\n";  
        System.out.println(text.replaceAll("(?m)^.*@@.*$(\r?\n|\r)?", ""));
    }
}

编辑:根据PSeed提到的,考虑到*nix、Windows和Mac的换行符。

谢谢Bart, 但是有没有办法获取字符串,而不包括与模式匹配的行呢?(我需要这个。) - Amit
2
是的,在我的 replaceAll(...) 示例中,我展示了如何做到这一点。 - Bart Kiers

3

有人提到要打开多行模式,但由于Java默认不支持DOTALL(单行模式),所以有一种更简单的方法...就是省略^和$。

String result = regex.replaceAll( ".*@@.*", "" );

请注意,使用此方法或以下方法存在问题:

"(?m)^.*@@.*$" 

...的问题在于它会保留空行。如果不允许有空行,则正则表达式将不同。

完整的正则表达式不会保留空行:

String result = regex.replaceAll( ".*@@.*(\r?\n|\r)?", "" );

2
正如另一位发帖者所指出的那样,在结尾添加\n?将替换而不留下空行...但如果您认为可能会出现DOS风格的换行符,则应该扩展为\r?\n?。 - PSpeed
谢谢,PSpeed,你能否提供一个正则表达式,以便返回没有空行的字符串。 - Amit

-1

请查看Matcher.matches()方法的JavaDoc:

boolean java.util.regex.Matcher.matches()
Attempts to match the entire input sequence against the pattern. 

If the match succeeds then more information can be obtained via the start, end, and group methods. 

Returns:
true if, and only if, the entire input sequence matches this matcher's pattern

首先尝试调用“matches”方法。这并不会像您的帖子中所述那样实际执行文本替换,但它可以让您更进一步。


-1

Java中是否有多行选项,请查看文档。至少在C#中有一个,我认为这可能是问题所在。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接