I want to replace i# (look that the example inputs/outputs) with the value of an array, but I’m not sure how to do this with Java+Regex.
Assume you have an array with: [3,2,1,0]
Example inputs:
i0
i1^2
(i1+2)+5
2*5+i1
i1+i2-i3
1+2
Example output:
3 [why? input is i0 and index 0 = 3 in the array]
2^2
(2+2)+5
2*5+2
2+1-0
1+2
Regex is here:
http://rubular.com/r/KXbCQnbs8K
REGEX = i{1}(\d+)
Code:
private String replace(String input){
StringBuffer s = new StringBuffer();
Pattern regex = Pattern.compile(REGEX);
Matcher m = regex.matcher(input);
if( !m.find(0) ){
return input;
}else{
m.reset();
}
while (m.find() ){
m.appendReplacement(s, getRealValue(m.group(1)) );
}
return s.toString();
}
private String getRealValue(String val){
int value = Integer.parseInt(val);
return String.valueOf(array.get(value));
}
Assume i#s given are always valid. My code works for some cases, but fails in most. Any help? Thanks!
EDIT:
I’m not sure how to tell it to add the last part (for example: +5 in i0+5).
i0 — works
i1^2 — doesn’t work
(i1+2)+5 — doesn’t work
2*5+i1 — works
i1+i2-i3 — doesn’t work
1+2 — works
1+i2 — works
I want to modify the regex to “i{1}(\d+)(.*)”
if(lastMatch()){ //if last match is true
s += m.group(2) //concat the last group (ie. “+5” in “i0+5”)
}
But I don’t know the correct syntax for that.
So it fails… what is it about the output that is being produced that is wrong? That’s a very useful bit of information that you’ve neglected to mentioned. In the future you should try to think more about why the output is wrong, this will help you to figure what the program is doing wrong.
But by the looks of it you’ve forgotten to use
Matcher.appendTail(StringBuffer)after you’ve done all the replacements.appendTailappends any remaining characters after the last match eg."i0[this bit]".I assume the wrong output was
i1^2 -> 2(i1+2)+5 -> (2Looking at this it would have been much faster to figure out what was going wrong. It’s forgetting to add last bit of String at the end. Let’s find a way to sort this out or read the API to see if there’s a method that does it in one simple step for me.
Example code