Search code examples
javaregexstringregex-group

How to make regex to check single quotes?


I want to replace only a single quote to double quotes but when I try it using regex it also replaces double quotes with two double quotes.

I used ([']) as regex but it returns true for double quotes also.

  • eg: when I passed -> don't : it is working correctly
  • but when I passed -> don''t : it is not working correctly final output became don''''t

I want to convert only single quotes to double quotes. How can I do this?


Solution

  • Apparently, by "double quotes", you mean "double single-quotes".

    You may use the following pattern:

    (?<!')'(?!')
    

    To find a single quote that's not followed or preceded by another single quote (using a negative Lookbehind and a negative Lookahead). Then you simply replace it with ''.

    Demo.

    Java example:

    String s = "don't, don''t";
    String output = s.replaceAll("(?<!')'(?!')", "''");
    System.out.println(output);   // Prints "dont''t don''t"
    

    Try it online.