How to use the Regex Tester
- Type a pattern, without the surrounding slashes, and choose its flags.
- Paste the text to test. Matches are highlighted as you type, and every match and capture group is listed.
- Turn on Replace to preview a replacement using
$1,$2or$<name>. - Copy the pattern as Apex
PatternandMatchercode when it works.
Testing a regular expression
Regular expressions are compact and unforgiving: one missing escape and the pattern matches far more, or far less, than you meant. Testing against real sample text, with every match highlighted, is the quickest way to get one right.
Flags
g(global): find every match, not just the first.i(ignore case):aalso matchesA.m(multiline):^and$match at the start and end of each line.s(dot all):.also matches line breaks.u(Unicode): treat the pattern and text as Unicode code points.y(sticky): match only at the current position.
Regular expressions in Apex
Apex uses Java’s regular expression engine through the Pattern and Matcher classes. Two things trip people up. First, every backslash must be doubled inside an Apex string, so \d becomes '\\d'. Second, flags are written inside the pattern, such as (?i) for ignore case.
Pattern p = Pattern.compile('(?i)\\b[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}\\b');
Matcher m = p.matcher(input);
while (m.find()) {
System.debug(m.group());
}For a simple yes-or-no check on the whole string, Pattern.matches(regex, input) is shorter. Note that it must match the entire input, unlike JavaScript’s test.
Avoiding catastrophic backtracking
Nested quantifiers such as (a+)+ can take exponential time on text that almost matches. In Apex this burns CPU time until the transaction hits its limit. If the tester stops a pattern for taking too long, rewrite it to remove the nesting or make the inner part more specific.
Features and limitations
What it does
- Live highlighting of every match, including zero-length matches, with positions and capture groups.
- Named groups, all JavaScript flags, and a replace preview.
- Runs patterns in a background worker with a time limit, so a runaway pattern cannot freeze the page.
- Converts the pattern to Apex with correct string escaping and inline flags such as
(?i). - A library of common patterns, including Salesforce record IDs.
What it does not do
- Patterns run with the JavaScript engine. Apex uses Java regular expressions, which differ in a few areas; the tool points these out.
- At most 1,000 matches are listed.
- It does not explain a pattern in plain language or generate one from examples.