Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

String Replace  RSS feed

 
Raj Guru
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
How replace the string that contains "(abc)" to "xyz".
Example
String s = "This is the (abc)" to "This is a Test".
The String.replaceAll and replaceFirst are unable replace.
Thanks
With regards
Josi
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably you are not using the replaceAll and replaceFirst methods correctly. Remember - a String object is immutable, what these methods do is create a new String with changed content - it is up to you to manage this new String.
Bill
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, these methods accept regular expressions as arguments; the parentheses will cause problems as they're special characters in regexps. You have to escape them with a double "\"; so combining William's and my suggestions, you need something like
String result = myString.replaceAll("\\(abc\\)", "xyz");
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that this is basically the same problem you asked about here, but with a different character that needs to be escaped. It's well worth your time to read the regex documentation carefully to understand how they work. Regexes can be extremely powerful, but there are a number of gotchas like this which can trap the unwary.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!