Hello everyone,
i have a problem using the replaceAll method and i hope that somebody can help. I want to remove substrings (sub) from a string (message). The message string looks like that:
prop(ag1,0,1,4,5)/prop(ag2,2,5,3,3)/prop(ag1,0,1,4,5)....
I want to take each prop(...) and put it in a list, but not the duplicate ones.
So i use
String sub = mess.substring(0,mess.indexOf('/'));
and then
mess=mess.replaceAll(sub,"");
but it doesn't work. I printed the mess after the replacement but it's the same and it hasn't removed the substrings. I tried to replace all the "(" just to check
mess=mess.replaceAll("(","r");
but i got that exception
java.util.regex.PatternSyntaxException: Unlcosed group near index 1
(
^.....
...

Does anyone know what's going on?

If you simply trying to replace one character like that, use the replace method:

class ReplaceAll
{
  public static void main(String[] args)
  {
	String s = "Replace /, /, and /";
	
	String replace = s.replace('/','r');

	
	System.out.println(replace);
  }
}

A common mistake is for people to expect replaceAll to literally replace all occurrances one string with another, but that's not what it does!
replaceAll() uses a regular expression to determine what to replace. If the string you're giving it as the pattern to replace doesn't compile to what you think it does it will give unexpected results.

Thank you. As i found out the problem is that characters '(' and ')' are treated as special characters by regex so one should use '"\\(" in the left part of the replaceAll in order to work.

i hve seen the above posts... u hve done a good job guys... i like to add that even "." is one of the special characters...

This article has been dead for over six months. Start a new discussion instead.