I want to use the $1 value like an integer.
The idea is to replace all numbers from originaltext with the equivalent array values and create a new text.
The below desired outcome should be "This is DBValue4, This is DBValue2, This is DBValue7"
Also, is there a way to save these backreferences for further use?
String[] values = {"DBValue0","DBValue1","DBValue2","DBValue3","DBValue4","DBValue5","DBValue6","DBValue7","DBValue8","DBValue9","DBValue10"};
String originaltext = "This is 4, This is 2, This is 7";
text = originaltext.replaceAll("(\\d)","$1");
// want something like
text = originaltext.replaceAll("(\\d)",values[$1]);
//or
text = originaltext.replaceAll("(\\d)",values[Integer.parseInt("$1")]);
You can use
Pattern
andMatcher
like so:Output:
EDIT
Further to the OP's comment is seems that the OP needs to replace
String
s of the form{name, index}
where "name" is the name of an array and "index" is the index of an element in that array.This is easily achieved by
Map
ping the arrays to their names using aMap<String, String[]>
and then using aPattern
that captures first thename
then theindex
.Output: