java - 替换包含正则表达式的行

标签 java regex string

我有一个包含多行的输入字符串(由\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.

我无法获取它,请帮帮我。

谢谢,
阿米特

最佳答案

为了让 ^ 匹配一行的开头,而 $ 匹配一行的结尾,您需要启用多行选项。您可以通过在您的正则表达式前面添加 (?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 换行符。

关于java - 替换包含正则表达式的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1762150/

相关文章:

regex - Elasticsearch 脚本正则表达式聚合

ruby-on-rails - 如何制作正则表达式来匹配所有互联网域(无论扩展名如何)

java - 子串索引范围

c - 使用 C 中的排序字典对字符串进行拼写检查

java - DynamoDB 排序并选择前 20 条记录

java - Socket.io 无需加入即可收听房间

java - 重构 Quartz 作业数据

java - 具有 namespace 解码的 JAXB(使用来自 REST 服务的 Jersey)

objective-c - Objective C 中使用正则表达式和 nsarray 进行字符串操作以及可变字符串

arrays - 检测字符串是否包含字符串数组的任何元素