I'm trying to replace pi with *pi using the following code, however it throws totally unexpected exception. How is the matcher looking at an index higher then String length?
private void makeEvaluationStringExpressionMXParserCompliant() {
Pattern multiply = Pattern.compile(mContext.getString(R.string.string_multiply));
Pattern pi = Pattern.compile(mContext.getString(R.string.string_pie));
Pattern e = Pattern.compile(mContext.getString(R.string.string_e));
Log.e("wingoku", "pi: "+ pi.toString() + " completeString: "+ mEvaluationStringExpressionBuilder.toString());
replaceAll(mEvaluationStringExpressionBuilder, pi, "*pi");
}
private void replaceAll(StringBuilder sb, Pattern pattern, String replacement) {
Matcher m = pattern.matcher(sb);
int start = 0;
while (m.find(start)) {
sb.replace(m.start(), m.end(), replacement);
start = m.start() + replacement.length();
}
}
Exception:
java.lang.IndexOutOfBoundsException: start=3; length=2
at java.util.regex.Matcher.find(Matcher.java:339)
at com.app.calculator.utils.StringExpressionFactory.replaceAll(StringExpressionFactory.java:68)
at com.app.calculator.utils.StringExpressionFactory.makeEvaluationStringExpressionMXParserCompliant(StringExpressionFactory.java:61)
at com.app.calculator.utils.StringExpressionFactory.createExpression(StringExpressionFactory.java:31)