正则表达式替换不在';'之后的所有换行符

时间:2014-03-23 11:53:15

标签: java regex

我想问一下是否有人可以帮助我使用正则表达式,该正则表达式将匹配\n以后\n以外的所有; 例如:

test
test1
test2;
test
test1;
test
test1;

将更改为

testtest1test2;
testtest1;
testtest1;

3 个答案:

答案 0 :(得分:1)

这个正则表达式可用于查找这些行:(?<!;)\n什么是基本上不是a;然后是新行。您还可以在\r?之前添加\n以接受回车(如果它们可以出现在您的文档中),但这取决于您的平台。

只需将匹配替换为""(空字符串)即可删除换行符。

答案 1 :(得分:0)

使用Look behinds,这应该有用 -

Search for   - (?<!;)\n
Replace with - (Empty string - '')

演示here

答案 2 :(得分:0)

您可以使用:

// read complete file in a string
String data = new Scanner(new File("file.txt")).useDelimiter("\\Z").next();

// remove all newlines that aren't preceded by semi-colon
String repl = data.replaceAll("(?<!;)(\\r?\\n)+", "");
相关问题