java中的正则表达式匹配和替换

java中的正则表达式匹配和替换,java,regex,pattern-matching,Java,Regex,Pattern Matching,我有一个有很多行的文件。中间可能会有空行。我希望匹配所有具有特定模式且后跟空换行符的行,并将其替换为仅包含该行(不包含以下空换行符)。没有图案但后面仍有空行的行将保持原样 样本文件 a + b --> c c + d --> e The empty line after this is left alone e + a --> b a --> b + c 输出文件 a + b --> c c + d --> e The empty line after

我有一个有很多行的文件。中间可能会有空行。我希望匹配所有具有特定模式且后跟空换行符的行,并将其替换为仅包含该行(不包含以下空换行符)。没有图案但后面仍有空行的行将保持原样

样本文件

a + b --> c

c + d --> e
The empty line after this is left alone

e + a --> b

a --> b + c
输出文件

a + b --> c
c + d --> e
The empty line after this is left alone

e + a --> b
a --> b + c
我有一个匹配所有这些线条的图案

String linePattern = "(.*-->.*)(\n\n)";
Pattern compiledPattern = Pattern.compile(linePattern);
Matcher matcher = compiledPattern.matcher(fileContentsAsString);

有没有一种优雅的方法可以从整个字符串中去掉这些行后面多余的空行?

实际上,这并不难:

(\w+\s+\+\s+\w+\s+-->\s+\w+|\w+\s+-->\s+\w+\s+\+\s+\w+)[\s\n\r]+(\w+\s+\+\s+\w+\s+-->\s+\w+|\w+\s+-->\s+\w+\s+\+\s+\w+)

可执行的


那么,您想在成功匹配后删除所有等待空间还是仅删除空白?成功匹配后将出现空行。只需在这些行中循环,仅复制所需的行。不要试图让你的代码太聪明。检查并修改。让我知道你是否能保留换行符,应该是
String subst=“$1\n$2”,带有一个反斜杠。
String regex = "(\\w+\\s+\\+\\s+\\w+\\s+-->\\s+\\w+|\\w+\\s+-->\\s+\\w+\\s+\\+\\s+\\w+)[\\s\\n\\r]+(\\w+\\s+\\+\\s+\\w+\\s+-->\\s+\\w+|\\w+\\s+-->\\s+\\w+\\s+\\+\\s+\\w+)";
String string = "a + b --> c\n\n"
     + "c + d --> e\n"
     + "The empty line after this is left alone\n\n"
     + "e + a --> b\n\n"
     + "a --> b + c";
String subst = "$1\n$2";

Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
Matcher matcher = pattern.matcher(string);
String result = matcher.replaceAll(subst);