Во-первых, я полностью согласен с мнением, что это не что-то, что должно делать регулярное выражение.
Вот демонстрационная версия Java:
public class Test {
public static String voodoo(String lines) {
return lines.replaceAll("\\G(.*\r?\n).*(?:\r?\n|$)", "$1");
}
public static void main(String[] args) {
System.out.println("a)\n"+voodoo("1\n2\n3\n4\n5\n6"));
System.out.println("b)\n"+voodoo("1\r\n2\n3\r\n4\n5\n6\n7"));
System.out.println("c)\n"+voodoo("1"));
}
}
output:
a)
1
3
5
b)
1
3
5
7
c)
1
Краткое объяснение регулярного выражения:
\G # match the end of the previous match
( # start capture group 1
.* # match any character except line breaks and repeat it zero or more times
\r? # match the character '\r' and match it once or none at all
\n # match the character '\n'
) # end capture group 1
.* # match any character except line breaks and repeat it zero or more times
(?: # start non-capture group 1
\r? # match the character '\r' and match it once or none at all
\n # match the character '\n'
| # OR
$ # match the end of the input
) # end non-capture group 1
\G
начинается в начале строки.Каждая пара строк (где вторая строка необязательна, в случае последней неровной строки) заменяется первой строкой в паре.
Но опять же: с использованием обычного языка программирования (если можно вызвать awk
"нормальный" :)) это путь.
РЕДАКТИРОВАТЬ
И, как предположил Тим, это также работает:
replaceAll("(?m)^(.*)\r?\n.*", "$1")