I need to replace a dynamic substring withing a larger string, but only once (i.e. first match). The String class provides only replace()
, which replaces ALL instances of the substring; there is a replaceFirst()
method but it only takes regexp instead of a regular string. I have two concerns with using regex:
1) my substring is dynamic, so might contain weird characters that mean something else in regex, and I don't want deal with character escaping.
2) this replacement happens very often, and I'm not sure whether using regex will impact performance. I can't compile the regex beforehand since the regex itself is dynamic!
I must be missing something here since this seems to me is a very basic thing... Is there a replaceFirst method taking regular string somewhere else in the java franework?
[rant] I have to say I'm surprised that, as the answer confirms, java framework does not offer such a basic method; sure it's easy to cook one up, but really? [/rant]