我有一个包含多行的输入字符串(由\ 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.
我无法得到它,请帮帮我。
谢谢,
阿米特
答案 0 :(得分: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换行符。
答案 1 :(得分:3)
其他人提到打开多线模式,但由于Java没有默认为DOTALL(单线模式),因此有一种更简单的方法......只需将^和$关闭。
String result = regex.replaceAll( ".*@@.*", "" );
请注意以下问题或使用:
"(?m)^.*@@.*$"
...是否会留下空行。如果要求没有它们,则正则表达式会有所不同。
不留空行的完整正则表达式:
String result = regex.replaceAll( ".*@@.*(\r?\n|\r)?", "" );
答案 2 :(得分:-1)
Java中是否有多行选项,请检查文档。在C#至少有一个,我认为这应该是问题。
答案 3 :(得分:-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
首先尝试调用“匹配”方法。这实际上不会像您的帖子中所述那样进行文本替换,但它会让您更进一步。