function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Yogesh Singh 32Yogesh Singh 32 

Increment digit value in String

I want to replace integers in "XYZ__3 AND XYZ__4" after size = 3 and expecting result "XYZ__4 AND XYZ__5"
 
String expression = 'XYZ__3 AND XYZ__4';
Integer size = 3;
Pattern p = Pattern.compile('(\\d{1,2})');
Matcher m = p.matcher(expression);

String next = '';
while (m.find()) {
   next = String.valueOf(size + 1);
   expression = expression.replaceAll(m.group(1), next);
   size++;
}

system.debug(expression);
But, I am getting "XYZ__5 AND XYZ__5". How can I achieve this using pattern and Matcher
 
bilal malikbilal malik
Actually when u run your code,
in first iteration, expression(string) will be changed from 'XYZ__3 AND XYZ__4' to 'XYZ__4 AND XYZ__4' 
in second iteration, expression(string) will be changed from 'XYZ__4 AND XYZ__4' to 'XYZ__5 AND XYZ__5' because now next=5 and m.group(1)=4, so it will replace 5 where 4 will occur in index because of replaceall function.
Yogesh Singh 32Yogesh Singh 32
I have solved this problem using following method:
 
public String getNextIntegerString(Integer size, String expression) {
        String result = expression;
        if(String.isNotBlank(expression) && size >= 0) {
            String next = '';
            result = '';
            Integer start = 0;
            Pattern p = Pattern.compile('(\\d{1,2})');
            Matcher m = p.matcher(expression);
            while (m.find()) {
                next = String.valueOf(size + 1);
                result = result + expression.substring(start, m.end() - m.group(1).length()) + next;
                size++;
                start = m.end();
            }
            result = result + expression.substring(start, expression.length());
        }
        return result;
    }