Search code examples
javaregexspecial-charactersreplaceall

Replace substring with some math characters from String - java


I have a math expression looks like String st = "((3-(5-2))+(2*(5-1)))"; and I want to replaceAll (5-1) with 4 and after that replaceAll (2*4) with 8 and... I haven't problem with replacing (5-1) with 4 but when I received to (2*4), as it has * star sign this code ( st.replaceAll("(2*4)", 8); ) doesn't work!

Could you help me to replaceAll expression that contains special characters.


Solution

  • You will have to attach "\" before "*" , for using in java, use one more "\".

    Also need to escape braces.

    public static void main(String[] args) {
            String st = "((3-(5-2))+(2*(5-1)))";
            st = st.replaceAll("(5-1)", "4");
            System.out.println(st);
            st = st.replaceAll("(2\\*\\(4\\))", "8");
            System.out.println(st);
        }
    

    Output

    ((3-(5-2))+(2*(4)))
    
    ((3-(5-2))+(8))