Using regular expressions in Apex

Using regex in Apex is one of the most frequently encountered requirements when we work on string manipulation a lot.

Have you ever encountered a situation where you need to process a string and filter out only certain parts of the text?

Let me give you a real-time scenario when a customer sends an email on processing the text of the email in case I find any matches (which has a specific pattern) then I need to mask it (or trigger some automation).

Can you think of any way to do this in Apex?

The only thing that you can think of would be Regular Expressions in this case.

But how do you use regex in Apex?

Out of the box we cannot, however, we have wrapper classes that are provided by the Apex team that we can use.

Let me give you another scenario.

If I find any language preference code(example en_US) in the URL then i need to trigger some automation, how am I gonna do it?

We will be using Patterns and matchers in Apex.

Here is the sample code snippet that might help you understand things better.

public void findMatch(){

	// below regex matches string that's in the format /en_US/
	String regExPattern = '\\/[a-z]{2}\\_[A-Z]{2}\\/';
    Pattern p = Pattern.compile(regExPattern);
    
    // string to be inspected
    String stringToInspect = 'https://www.salesforcecasts.com/en_US/courses';
    Matcher pm = p.matcher(stringToInspect);

        if( pm.matches() ){
			// yes, lang pref code exists
            // business logic
        }
}        
Using regular expressions in Apex

Hope this is helpful!