A pattern is a compiled representation of a regular expression. Patterns are used by matchers to perform match operations on a character string.
A regular expression is a string that is used to match another string, using a specific syntax. Apex supports the use of regular expressions through its Pattern and Matcher classes.
Many Matcher objects can share the same Pattern object, as shown in the following illustration:
Regular expressions in Apex follow the standard syntax for regular expressions used in Java. Any Java-based regular expression strings can be easily imported into your Apex code.
All regular expressions are specified as strings. Most regular expressions are first compiled into a Pattern object: only the String split method takes a regular expression that isn't compiled.
// First, instantiate a new Pattern object "MyPattern" Pattern MyPattern = Pattern.compile('a*b'); // Then instantiate a new Matcher object "MyMatcher" Matcher MyMatcher = MyPattern.matcher('aaaaab'); // You can use the system static method assert to verify the match System.assert(MyMatcher.matches());
If you are only going to use a regular expression once, use the Pattern class matches method to compile the expression and match a string against it in a single invocation. For example, the following is equivalent to the code above:
Boolean Test = Pattern.matches('a*b', 'aaaaab');