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 :)
.
source to share
Apache Jakarta Commons are often the solution to this class of problems. In this case, I would look at commons-lang , espacially StringUtils.replaceOnce () .
source to share
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.
source to share