Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Matcher.appendReplacement() and Matcher.appendTail() for StringBuilder?

Tags:

java

Is there an alternative to Matcher.appendReplacement() and Matcher.appendTail() which takes StringBuilder instead of StringBuffer ?

Is there an 'easy' way to 'convert' Java code which calls Matcher with a StringBuffer to use StringBuilder instead?

Thanks, James

like image 575
James Avatar asked Jul 14 '16 14:07

James


2 Answers

Short answer, not yet. Not until Java 9. In Java 9 there are Matcher.appendReplacement(StringBuilder,String) and Matcher.appendTail(StringBuilder) methods added to the API.

Until then if you don't need group substitutions in replacement string then I still find this solution 'easy':

Matcher m = PATTERN.matcher(s);
StringBuilder sb = new StringBuilder();
int pos = 0;
while(m.find()) {
    sb.append(s, pos, m.start());
    pos = m.end();
    sb.append("replacement")
}
sb.append(s, pos, s.length());

And even if you need group subtitutions then it gets just 'moderately' difficult:

Matcher m = PATTERN.matcher(s);
StringBuilder sb = new StringBuilder();
int pos = 0;
while(m.find()) {
    sb.append(s, pos, m.start());
    pos = m.end();
    if (m.start(1) >= 0) {                  // check if group 1 matched
        sb.append(s, m.start(1), m.end(1)); // replace with group 1
    }
}
sb.append(s, pos, s.length());
like image 138
mmm444 Avatar answered Oct 27 '22 12:10

mmm444


Short answer, no.

This is as per API in latest Java 8 at the time of writing.

However, one of the overloaded StringBuffer constructors takes a CharSequence as parameter, and StringBuilder (just like StringBuffer) IS-A CharSequence.

For instance:

matcher.appendReplacement(
    new StringBuffer(yourOriginalStringBuilder), "yourReplacement"
);

Edit

Since Java 9, an overload is available, which takes a StringBuilder instead - see API here.

like image 4
Mena Avatar answered Oct 27 '22 12:10

Mena