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'
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'
Use this regex (?<!\?)'
in split funtion
String s="HJK'ABCP?'QR2'SER'";
System.out.println(s.replaceAll("(?<!\\?)'","\r\n"));