How to replace string only once without regex in Java?

Viewed 20070

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?

7 Answers
Related