0

I want to replace "<(><<)>" with "<" but its not replacing in my case.

public class Test2 {

public static void main(String[] args)
    {
        String s1 = "<(><<)>script>";

       if( s1.contains("<(><<)>"))
       {
        s1.replaceAll("<(><<)>","<");
         }


    System.out.println("completeText"+s1);

    }

}

2 Answers 2

2

That's because

  • the first parameter of replaceAll is a regular expression, which implies you have to escape some chars.
  • you have to get back the result (strings are immutable, so replaceAll doesn't change the string you pass but builds a new one)

Use

 s1 = s1.replaceAll("<\\(><<\\)>","<");

Note also that you don't have to test if( s1.contains("<(><<)>")) : this adds a useless condition and replaceAll is fast enough.

Sign up to request clarification or add additional context in comments.

Comments

1

String.replaceAll method takes the first parameter as Regex. So, you need to escape your (, and ) which have special meaning in Regex.

Alternatively, you can use Pattern.quote method to escape your special characters for you. Also, you need to store the return value of replaceAll method in your string s1. Since Strings in Java are immutable, so any method of String class you invoke, returns a modified string. You need to make use of the return value, else you won't see any changes.

So, you need to modify your code as:-

s1 = s1.replaceAll(java.util.regex.Pattern.quote("<(><<)>"),"<");

This will automatically replace your pattern if it is present in the string, else it returns an unmodified string.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.