Java 替换包含正则表达式的行
我有一个包含多行的输入字符串(由\n分隔)。我需要在行中搜索一个模式,如果找到了,则用空字符串替换整个行 我的代码是这样的Java 替换包含正则表达式的行,java,regex,string,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 \
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为了让
^
匹配行的开头和$
匹配行的结尾,您需要启用多行选项。您可以通过在正则表达式前面添加(?m)
,如下所示:“(?m^.*.@.*$”
此外,您希望在正则表达式查找匹配项时保持分组,可以这样做:
while(m.find()) {
System.out.println("Output: "+m.group());
}
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)?", ""));
}
}
注意正则表达式将匹配这些行(而不是您指定的行):
但是如果你想替换包含@
的行,正如你文章的标题所建议的那样,可以这样做:
while(m.find()) {
System.out.println("Output: "+m.group());
}
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中有多行选项,请检查文档。至少在C语言中有一种,我认为这应该是问题所在。其他人提到打开多行模式,但由于Java没有默认为DOTALL(单行模式),所以有一种更简单的方法。。。只需去掉“^”和“$”就行了
String result = regex.replaceAll( ".*@@.*", "" );
请注意,此问题或使用:
"(?m)^.*@@.*$"
<>……它会留下空行。如果要求不使用它们,则正则表达式将有所不同
不留空行的完整正则表达式:
String result = regex.replaceAll( ".*@@.*(\r?\n|\r)?", "" );
查看Matcher.matches()方法上的JavaDoc:
首先尝试调用“matches”方法。这实际上不会像你在文章中提到的那样进行文本替换,但会让你走得更远。正如另一张海报所指出的,添加\n?最后将替换,不留空行。。。虽然应该扩展到\r?\n?如果你认为你可能会得到DOS风格的线条结尾。谢谢,PSpeed,你能给ReGEX,它返回字符串而不留下空行。谢谢Bart,但是有没有办法得到字符串,没有与模式匹配的线。(我需要这个。)是的,我展示了如何在我的<代码> RePoTALL(…)< /代码>例子中做到这一点。