0

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'

Tom
  • 16,842
  • 17
  • 45
  • 54
shefali
  • 19
  • 3

3 Answers3

0

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'
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
0

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

Issam El-atif
  • 2,366
  • 2
  • 17
  • 22
0
String s="HJK'ABCP?'QR2'SER'";

        System.out.println(s.replaceAll("(?<!\\?)'","\r\n"));
Keval Pithva
  • 600
  • 2
  • 5
  • 21