How to separate a string into multiple lines based

2019-09-04 09:38发布

问题:

This question already has an answer here:

  • Regex lookahead, lookbehind and atomic groups 3 answers

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'

回答1:

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'


回答2:

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



回答3:

String s="HJK'ABCP?'QR2'SER'";

        System.out.println(s.replaceAll("(?<!\\?)'","\r\n"));