Search code examples
javareplaceall

How should I do to replace the double quotation mark following a number only?


For example, the target string is: AAA"AAA"AAAA 18" x 18" bbb"". The target string after replacement should be : AAA"AAA"AAAA 18 inches x 18 inches bbb"".


Solution

  • You could have the following regular expression:

    public static void main(String[] args) {
        String str = "AAA\"AAA\"AAAA 18\" x 18\" bbb\"\"";
        String replaced = str.replaceAll("(\\d+)\"", "$1 inches");
        System.out.println(replaced); // prints AAA"AAA"AAAA 18 inches x 18 inches bbb""
    }
    

    This code replaces all digits followed by a quote " with those digits (using the back reference $1) and inches. As such, this makes sure that only quotes after digits are replaced.