Problem: Turn
"My Testtext TARGETSTRING My Testtext"
into
"My Testtext targetstring My Testtext"
Perl supports the “\L”-operation which can be used in the replacement-string.
The Pattern-Class does not support this operation:
Perl constructs not supported by this class:
[…]
The preprocessing operations \l \u, \L, and \U.
https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html
You can’t do this in Java regex. You’d have to manually post-process using
String.toUpperCase()andtoLowerCase()instead.Here’s an example of how you use regex to find and capitalize words of length at least 3 in a sentence
Note on
appendReplacementandappendTailNote that the above solution uses
substringand manages atailindex, etc. In fact, you can go without these if you useMatcher.appendReplacementandappendTail.Note how
sbis now aStringBufferinstead ofStringBuilder. UntilMatcherprovidesStringBuilderoverloads, you’re stuck with the slowerStringBufferif you want to use these methods.It’s up to you whether the trade-off in less efficiency for higher readability is worth it or not.
See also
StringBuilderandStringBufferin Java