I found String.replaceAll() in Java with regular expression underlying. It works fine in short string.
But in case of long string, I need a more efficient algorithm instead of String.replaceAll().
Anyone could give advice?
Thanks!
I found String.replaceAll() in Java with regular expression underlying. It works fine in short
Share
If you want to do incremental replacement, you can use an explicit
appendReplacement/Tailloop to aStringBuffer(unfortunately noStringBuilderoverloads as of yet).Here’s the idiom from the documentation:
This is pretty much how
replaceAllis implemented.The benefit of this method is that since you have full control over the replacement iteration, you don’t have to store the entire output in memory at any given time as a potentially long
String. You can incrementally build the output, flushing theStringBuffercontent to the disk periodically. That is, using this method can be more memory efficient than usingreplaceAll.(You can also do fancy replacements that is not supported by the current replacement syntax, e.g.
toUpperCase()transformation).Note that there is a request for enhancement for
Matcherto be able to append to anyAppendable. If granted, not only can you useStringBuilder, but you can also directly replace to e.g. aFileWriter.Related questions
StringBuilderandStringBufferin JavaSee also
Matchershould make more use ofAppendableMatcherto append to anyAppendable