5

In below line if we have single quote (') then we have to replace it with '||''' but if we have single quote twice ('') then it should be as it is.

I tried below piece of code which is not giving me proper output.

Code Snippet:

static String replaceSingleQuoteOnly = "('(?!')'{0})";
String line2 = "Your Form xyz doesn't show the same child''s name as the name in your account with us.";
System.out.println(line2.replaceAll(replaceSingleQuoteOnly, "'||'''"));

Actual Output by above code:

Your Form xyz doesn'||'''t show the same child''||'''s name as the name in your account with us.

Expected Result:

Your Form xyz doesn'||'''t show the same child''s name as the name in your account with us.

Regular expression is replacing child''s with child''||'''s. child''s should remain as it is.

Sanjay Madnani
  • 803
  • 7
  • 16

2 Answers2

5

You can use lookarounds for this, e.g.:

String replaceSingleQuoteOnly = "(?<!')'(?!')";
String line2 = "Your Form xyz doesn't show the same child''s name as the name in your account with us.";
System.out.println(line2.replaceAll(replaceSingleQuoteOnly, "'||'''"));
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
  • Thanks Darshan for the solution. I still have some issues with regular expression in my code which I have posted here: http://stackoverflow.com/q/42935679/3525348 Could you please help me on it. – Sanjay Madnani Mar 21 '17 at 18:52
4

add a negative look behind to assure that there is no ' character before another ' and remove extra capturing group ()

so use (?<!')'(?!')

    String replaceSingleQuoteOnly = "(?<!')'(?!')";
    String line2 = "Your Form xyz doesn't show the same child''s name as the name in your account with us.";
    System.out.println(line2.replaceAll(replaceSingleQuoteOnly, "'||'''"));

Output :

Your Form xyz doesn'||'''t show the same child''s name as the name in your account with us.

As per Apostrophe usage you can simply use (?i)(?<=[a-z])'(?=[a-z]) to find ' surrounded by alphabets

    String replaceSingleQuoteOnly = "(?i)(?<=[a-z])'(?=[a-z])";
    String line2 = "Your Form xyz doesN'T show the same child''s name as the name in your account with us.";
    System.out.println(line2.replaceAll(replaceSingleQuoteOnly, "'||'''"));
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68