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

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

I tried below a piece of code that does not give me the correct output.

Code snippet:

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

Actual output from the code above:

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

Expected Result:

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

The regular expression replaces child ' with child' '||' '' s . the child's must remain as he is.

+5
source share
2 answers

You can use lookarounds , for example:

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

add a negative appearance to make sure that before ' no character ' and remove the extra capture group ()

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

  String replaceSingleQuoteOnly = "(?<!')'(?!')"; String line2 = "Your Form xyz doesn't show the same child' 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' name as the name in your account with us. 

According to Apostrophe you can just use (?i)(?<=[az])'(?=[az]) to find ' surrounded by alphabets

  String replaceSingleQuoteOnly = "(?i)(?<=[az])'(?=[az])"; String line2 = "Your Form xyz doesN'T show the same child' name as the name in your account with us."; System.out.println(line2.replaceAll(replaceSingleQuoteOnly, "'||'''")); 
+4
source

Source: https://habr.com/ru/post/1265648/


All Articles