954,518 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Problem with String replaceAll method

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?

kratoras
Newbie Poster
2 posts since Mar 2005
Reputation Points: 10
Solved Threads: 0
 

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);
  }
}
server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

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.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

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.

kratoras
Newbie Poster
2 posts since Mar 2005
Reputation Points: 10
Solved Threads: 0
 

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...

Rajesh1202
Newbie Poster
1 post since Sep 2010
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You