How to use Regex using apex in Salesforce?

Regular expressions (REGEX) is a string that is used to match another string, using a specific syntax. Apex provides patterns and matchers that enable you to search text using regular expressions.

Pattern Class: A pattern is a compiled representation of a regular expression. Patterns are used by matchers to perform match operations on a character string.

Matcher Class: It allows to do further actions such as checking to see if the string matched the pattern or allows to manipulate the original string in various ways and produce a new desired one.

Let’s take one simple example:

public Boolean ValidateEmail(String emailId) 
{
    Boolean result = false;
    String emailRegex = '^[a-zA-Z0-9._|\\\\%#~`=?&/$^*!}{+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$';
    Pattern EmailPattern = Pattern.compile(emailRegex);
    Matcher EmailMatcher = EmailPattern.matcher(emailId);
    if(EmailMatcher.matches())
    {
        result = true;
    }
    return result;
}

In above example ValidateEmail is a method with emailId parameter. In ValidateEmail method there is a string variable, which contains email validation regex. Then I create matching pattern by using the pattern class with emailRegex variable. Then I do match it against the emailId. After that I do check emailId variable is in valid email format.