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
  • 15,514
  • 17
  • 42
  • 51
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
  • 50,694
  • 8
  • 64
  • 113
0

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

Issam El-atif
  • 1,980
  • 2
  • 14
  • 20
0
String s="HJK'ABCP?'QR2'SER'";

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