Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.
Using Patterns and Matchers
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.
1// First, instantiate a new Pattern object "MyPattern"
2Pattern MyPattern = Pattern.compile('a*b');
3
4// Then instantiate a new Matcher object "MyMatcher"
5Matcher MyMatcher = MyPattern.matcher('aaaaab');
6
7// You can use the system static method assert to verify the match
8System.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:
1Boolean Test = Pattern.matches('a*b', 'aaaaab');