[SalesForce] Regex Search-and-Replace with Capture Groups

In IDEs a common operation is to perform a search and replace operation using a regex pattern in the search field and another pattern with capture groups in the replacement field.

For example, I can search for (\d)(\D)(\d) and replace it with first: \1; second: \2; third: \3. This would produce the following results.

  • "1a2" => "first: 1; second: a; third: 2"
  • "8o8" => "first: 8; second: o; third: 8"

Is there an easy way to perform this same operation on a String object in Apex? I'm looking for a solution that isn't hard-constrained to only process three capture groups. The number of capture groups is variable: could be 2, 3, 5 or any number.

Best Answer

There are Matcher and Pattern classes, that can be used to use regex. for example the following code does, that you want

String toCheck = '1a2';
Map<Integer, String> descriptionToGroupNumber = new Map<Integer, String>{
    1 => 'first',
    2 => 'second',
    3 => 'third',
    4 => 'fourth',
    5 => 'fifth'
};
Pattern pat = Pattern.compile('(\\d)(\\D)(\\d)');
Matcher match = pat.matcher(toCheck);
Integer groupsToCapture = match.groupCount();
while(match.find()){
    String output = '';
    for(Integer i = 1; i <= groupsToCapture; i++){
        if(i != 1){
           output +=' '; 
        }
        output +=descriptionToGroupNumber.get(i)+': '+ match.group(i);
        if(i != groupsToCapture){
           output+=';';
        }
    }
    System.debug(output);  
}

output is

DEBUG|first: 1; second: a; third: 2

\1 equals to capturing specific group match.group(1)

Related Topic