0

I am trying to replace all occurrences of the special character with new line except when there is a ? character preceeding the character.Input string is HJK'ABCP?'QR2'SER' and want the output as

HJK'
ABCP?'QR2'
SER'

Code:

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

I get o/p as expected:-

HJK'
ABCP?'QR2'
SER'

Problem is the special character could vary and has to be replaced with new line (expcept when preceeded by ?)

str.replaceAll("(?

doesn't work for all cases.eg. doesn't work as expected when character is * or [

Can anyone tell what's wrong?

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
shefali
  • 19
  • 3
  • 1
    You need to quote the character: `Pattern.quote(character)`. You should also quote the replacement. – Andy Turner Feb 13 '17 at 06:50
  • I wouldn't use a regex for this. Just build it up in a `StringBuilder`, looping over the characters in the input. – Andy Turner Feb 13 '17 at 06:52
  • Possible duplicate of [How to separate a string into multiple lines based on a separator but not if it is preceded by '?'](http://stackoverflow.com/questions/40238984/how-to-separate-a-string-into-multiple-lines-based-on-a-separator-but-not-if-it) – shmosel Feb 13 '17 at 07:08
  • It's a different question.Not a duplicate – shefali Feb 13 '17 at 09:09

0 Answers0