1

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

3 Answers 3

10

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.

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

1 Comment

Compiles fine for me - check that you haven't made the same error elsewhere.
5

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");

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.