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