tags:

views:

231

answers:

3

hi all,

I have following string

String str = "replace :) :) with some other string";

And I want to replace first occurance of ':)' with some other string

And I used str.replaceFirst(":)","hi");

it gives following exception

"Unmatched closing ')'"

I tried using replace function but it replaced all occurance of ':)'.

+8  A: 

The replaceFirst method takes a regular expression as its first parameter. Since ) is a special character in regular expressions, you must quote it. Try:

str.replaceFirst(":\\)", "hi");

The double backslashes are needed because the double-quoted string also uses backslash as a quote character.

Greg Hewgill
i tried using this also but its throws same exception...
Compiles fine for me - check that you haven't made the same error elsewhere.
matt b
+1  A: 

Apache Jakarta Commons are often the solution for this class of problems. In this case, I would have a look at commons-lang, espacially StringUtils.replaceOnce().

Guillaume
+5  A: 

The first argument to replaceFirst() is a regular expression, not just a character sequence. In regular expressions, the parantheses have special significance. You should escape the paranthesis like this:

str = str.replaceFirst(":\\)", "hi");
Tor Haugen