Extract string using Regular Expression in Salesforce Apex

This is achievable with the help of Regular Expression with Apex Pattern and Matcher Classes and below is the some examples:

1). Validate Email Address using Regular Expression in Salesforce Apex:
String InputString = ‘info@theblogreaders.com’;
String emailRegex = ‘([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})’;
Pattern MyPattern = Pattern.compile(emailRegex);

// Then instantiate a new Matcher object “validEmailAddress”
Matcher validEmailAddress = MyPattern.matcher(InputString);

if (!validEmailAddress.matches()) {
// invalid, do something
2). Match String values using Regular Expression in Salesforce Apex:

String candidate = ‘A0B1C2’;
Pattern p = Pattern.compile(‘[A-Z][0-9][A-Z][0-9][A-Z][0-9]’);
Boolean b = p.matcher(candidate).matches();

3). Remove HTML Tags in String using Regular Expression in Salesforce Apex:

string html = ‘<b>thebloderreaders.com</b>’;
//first replace all <BR> tags with \n to support new lines
string result = html.replaceAll(‘<br/>’, ‘\n’);
result = result.replaceAll(‘<br />’, ‘\n’);

//regular expression to match all HTML/XML tags
string HTML_TAG_PATTERN = ‘<.*?>’;

// compile the pattern
pattern myPattern = pattern.compile(HTML_TAG_PATTERN);

// get your matcher instance
matcher myMatcher = myPattern.matcher(result);

//remove the tags
result = myMatcher.replaceAll(”);
Output: thebloderreaders.com

4). Here are some examples to extract the string value using Regular Expression in Salesforce Apex
(foo|bar) – search for ‘foo’ OR ‘bar’
[a-z^kb] – search for any lowercase letter, but not k and not b
[A-Z^KB] – search for any uppercase letter, but not k and not b
^foo – search for ‘foo’, but only at the beginning of the line
bar$ – search for ‘bar, but only at the end of the line
Reference of Java regular expressions:

Important Links for the Patterns and Matchers in Apex Class:

Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript Tool: https://regex101.com/

Written by 

I am Sakthivel Madesh, a certified Salesforce Advanced Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 15x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead 5x Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply

Your email address will not be published. Required fields are marked *