开发者

Successive appendReplacement calls fail

3 groups in the regular expression:

pattern = (a)(b)123(c)

I need to get rid of a,b,c

in Java:

while (matcher.find()) {
  matcher.appendReplacement(sb, "");
  matcher.appendReplacement(sb, ""); // fails from here
  matcher.appendReplacement(sb, "");
}

exception:

java.lang.StringIndexOutOfBoundsException: String index out of range: -30
    at java.la开发者_StackOverflowng.String.substring(Unknown Source)
    at java.lang.String.subSequence(Unknown Source)
    at java.util.regex.Matcher.getSubSequence(Unknown Source)
    at java.util.regex.Matcher.appendReplacement(Unknown Source)

Is there a way to successively replace the matched groups?

EDIT: sb is a StringBuffer. Both empty new StringBuffer() and non-emtpy new StringBuffer(target_text_str) have been tried.

java 1.6.0_21-b07


You should have only one appendReplacement() call per find() call:

while (matcher.find()) {
  matcher.appendReplacement(sb, "");
}

This would remove each entire match in your input.

If, as you indicated, you want to remove some parts of the match, then you must group the part that you want to keep and add that to the replacement. Using the pattern ab(123)c you'd do this:

while (matcher.find()) {
  matcher.appendReplacement(sb, "$1");
}

If you need the other groups for some other reasons (for example you need to evaluate them), then you can keep them (i.e. use (a)(b)(123)(c) and reference the third group using $3 instead of $1).


pattern = "(a)(b)(123)(c)"

// ...

while (matcher.find()) {
  matcher.appendReplacement(sb, "$3");
}

See the docs

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜