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.lang.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 perfind()call: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)cyou’d do this: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$3instead of$1).