Leveraging Regular Expressions in Apex

The utilization of regular expressions in Apex is a common requirement, especially when extensively dealing with string manipulation tasks.

Have you ever encountered a situation where you needed to process a string and extract specific parts of the text?

Consider a real-time scenario: when a customer sends an email, there’s a need to process the email text. If any matches are found, indicating a specific pattern, it’s necessary to either mask the information or trigger some automation.

How could you approach this in Apex?

The most plausible solution in such cases would be to use Regular Expressions.

However, using regex directly in Apex is not supported out of the box. Instead, Apex provides wrapper classes that can be employed for this purpose.

Let’s explore another scenario: if a language preference code (e.g., en_US) is identified in the URL, there is a need to trigger certain automation. How can this be accomplished?

In this case, we’ll be utilizing Patterns and Matchers in Apex.

Here’s a sample code snippet that may enhance your understanding of these concepts.

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
        }
}