java.util.regex.Matcher and StringBuilder/StringBuffer APIs

Robert Marcano robert at marcanoonline.com
Fri Jun 21 18:30:31 UTC 2019


On 6/21/19 1:02 PM, Rob Spoor wrote:
> Maybe because Appendable comes with IOExceptions?

Good catch. The alternative Appendable I was using don't declare throws 
IOException either, so I didn't noticed.

Implementing the find/appendReplacement/appendTail for other kind of 
Appendable like objects on client code instead of the JDK is not hard, 
the only part missing is access to the appendExpandedReplacement() 
implementation as some kind of API, It parses the replacement pattern 
and generate the replacement.

Another interesting thing is that appendReplacement() is using a 
temporary StringBuilder [1] instead of appending directly to the 
supplied builder. The only reason I see for that is that if the pattern 
is illegal, the intervening text isn't appended, so the client code can 
retry, or something like that, but I don't think it is common or 
recommended to be capturing IllegalArgumentException for something like 
this. I wonder if changing it to not use a temporary builder makes sense.


[1] 
http://hg.openjdk.java.net/jdk/jdk/file/e764228f71dc/src/java.base/share/classes/java/util/regex/Matcher.java#l997

> 
> 
> On 21/06/2019 17:06, Robert Marcano wrote:
>> Greetings. Is there a reason the newest APIs added to Matcher 
>> (performance maybe?) with StringBuilder arguments weren't added as 
>> Appendable instead?
>>
>> For example:
>>
>>    public StringBuilder appendTail(StringBuilder sb)
>>    public Matcher appendReplacement(StringBuilder sb, String replacement)
>>
>> Could have been:
>>
>>    public <T extends Appendable> T appendTail(T ap)
>>    public Matcher appendReplacement(Appendable ap, String replacement)
>>
>> Both appendReplacement(...) implementations are copies, that could be 
>> reduced to a simple one if Appendable was the argument, and the 
>> present ones calling to that.
>>
>> If this sounds reasonable, I could write a patch for testing.
>>
>> Note: I was hit with this when trying to use another kind of 
>> Appendable optimized for my use case.
>>



More information about the core-libs-dev mailing list