How to separate a string into multiple lines based

2019-09-04 09:50发布

This question already has an answer here:

I am trying to separate a string into multiple lines based on separator ' but if there's a ? character before ' I want the data to remain in the same line.

Initial String:

HJK'ABCP?'QR2'SER'

I am able to print the lines like:

HJK'
ABCP?'
QR2'
SER'

But I want the output as:

HJK'
ABCP?'QR2'
SER'

3条回答
啃猪蹄的小仙女
2楼-- · 2019-09-04 10:04
String s="HJK'ABCP?'QR2'SER'";

        System.out.println(s.replaceAll("(?<!\\?)'","\r\n"));
查看更多
我命由我不由天
3楼-- · 2019-09-04 10:15

Use this regex (?<!\?)' in split funtion

查看更多
劳资没心,怎么记你
4楼-- · 2019-09-04 10:26

You need a negative lookbehind (http://www.regular-expressions.info/lookaround.html) :

String str = "HJK'ABCP?'QR2'SER'";
System.out.println(str);
System.out.println("---------------");
System.out.println(str.replaceAll("'", "'\r\n"));
System.out.println("---------------");
System.out.println(str.replaceAll("(?<!\\?)'", "'\r\n"));

It returns :

HJK'ABCP?'QR2'SER'
---------------
HJK'
ABCP?'
QR2'
SER'

---------------
HJK'
ABCP?'QR2'
SER'
查看更多
登录 后发表回答