我有一个包含多行的输入字符串(由\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());
Run Code Online (Sandbox Code Playgroud)
我希望回复如下:
Output: This is the first line
And this is second line
This is 3rd line and should come
But this will appear.
Run Code Online (Sandbox Code Playgroud)
我无法得到它,请帮帮我.
谢谢,
阿米特
为了使^匹配成为行的开头并$匹配行的结尾,您需要启用多行选项.你可以通过(?m)在你的正则表达式前添加如下:"(?m)^.*@@.*$".
此外,您希望在正则表达式找到匹配时保持分组,这可以这样做:
while(m.find()) {
System.out.println("Output: "+m.group());
}
Run Code Online (Sandbox Code Playgroud)
请注意,正则表达式将匹配这些行(而不是您指定的行):
Thus is @@{xyz} should not appear
This will not appear @@{abc}
Run Code Online (Sandbox Code Playgroud)
但是如果你想要替换包含的行@@,就像你帖子的标题所暗示的那样,那样做:
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)?", ""));
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:占PSeed提到的*nix,Windows和Mac换行符.