Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace ' (single quote once) but not '' (single quote twice) with '||'''

Tags:

java

regex

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.

like image 283
Sanjay Madnani Avatar asked Mar 18 '17 17:03

Sanjay Madnani


2 Answers

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, "'||'''"));
like image 92
Darshan Mehta Avatar answered Nov 16 '22 18:11

Darshan Mehta


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, "'||'''"));
like image 32
Pavneet_Singh Avatar answered Nov 16 '22 20:11

Pavneet_Singh