I am trying to replace all digits with {digit}
, but the issue is double digits are getting replaced incorrectly.
For eg:
String str = '1 AND 2 OR (3)';
Pattern p = Pattern.compile('([0-9]+)');
Matcher m = p.matcher(str);
while(m.find()) {
Integer value = Integer.valueOf(m.group(0));
str = str.replace(String.valueOf(value), '{'+value+'}');
}
System.debug(str);
Output:
21:39:00.24 (31729762)|USER_DEBUG|[9]|DEBUG|{1} AND {2} OR ({3})
But when there is a double digit, it does not get replaced properly.
String str = '1 AND 2 OR (13)';
Pattern p = Pattern.compile('([0-9]+)');
Matcher m = p.matcher(str);
while(m.find()) {
Integer value = Integer.valueOf(m.group(0));
str = str.replace(String.valueOf(value), '{'+value+'}');
}
System.debug(str);
Output: 21:39:52.28 (36494477)|USER_DEBUG|[9]|DEBUG|{1} AND {2} OR ({1}3)
I tried this too Pattern.compile('([0-9]+){1,2}');
but not successful.
Is there a way to compile a regex to consider single and double digits too?