All posts

REGEX in Apex

This blog explains how to use REGEX in Apex to check for valid email addresses. There are two classes Pattern and Matcher which are used to create a pattern and match a value respectively. Please follow the below steps:

1. REGular EXpression to check for valid email address.
([a-zA-Z0-9_\\-\\.]+)@(((\\[a-z]{1,3}\\.[a-z]{1,3}\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3}))
2. Use "Compile" method of Pattern class to create a pattern by passing the above regular expression.
Pattern p = Pattern.compile( '([a-zA-Z0-9_\\-\\.]+)@(((\\[a-z]{1,3}\\.[a-z]{1,3}\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3}))');
3. Use "Matcher" method of Pattern class to create a matcher.
Matcher m = p.matcher(emailAddress);
4. Use "Matches" method of Matcher class to check whether an email address matches the pattern or not. This method returns boolean: True if the email matches and False if the email is invalid.
Boolean isValid = m.matches();
5. Compiled code sample:
Pattern p = Pattern.compile( '([a-zA-Z0-9_\\-\\.]+)@(((\\[a-z]{1,3}\\.[a-z]{1,3}\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3}))');
String[] emailAddressList = new String[]{'test@test.com', 'test1.test.com', 'test2@test.com', 'test-3@test.com', 'test4-test.com'};
for (String emailAddress : emailAddressList) {
System.debug('Email address: ' + emailAddress);
Matcher m = p.matcher(emailAddress);
if (m.matches()) {
System.debug('Valid email address. Email domain: ' + m.group(2));
} else {
System.debug('Invalid email address!');
}
}

First published on Blogger in 2017. Some screenshots and APIs have changed since; the code is kept as written.

  • apex
  • check for valid email address
  • matcher
  • pattern
  • regex
  • regular expression
  • Salesforce