String replacement function

I have a line

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

      

And I want to replace the first occurrence :)

with another line

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

gives the following exception

"Unbeatable closure") "

I tried using the function replace

, but it replaced all events :)

.

+1


source to share


3 answers


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



+1


source


The method replaceFirst

takes a regular expression as its first parameter. Since it )

is a special character in regular expressions, you must quote it. Try:

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

      



A double backslash is required because a double quoted string also uses a backslash as the quote character.

+10


source


The first argument to replaceFirst () is a regular expression, not just a sequence of characters. In regular expressions, parentheses have a special meaning. You should avoid paradelation as follows:

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

      

+5


source







All Articles