regex-recursion
This is an extension for the regex
template tag that adds support for recursive patterns up to a specified max depth N, where N must be 2–100.
You can add recursion to a regex pattern via one of the following:
(?R=N)
— Recursively match the entire pattern at this position.\g<name&R=N>
— Recursively match the contents of group name at this position. The \g
subroutine must be used within the referenced group.
Any backreferences are unique per depth level.
Examples
Match an equal number of two different patterns:
import {rregex} from 'regex-recursion';
rregex`a(?R=50)?b`.exec('test aaaaaabbb')[0];
Match an equal number of two different patterns, as the whole string:
const re = rregex`
^
(?<balanced>
a
# Recursively match just the specified group
\g<balanced&R=50>?
b
)
$
`;
re.test('aaabbb');
re.test('aaabb');
Match balanced parentheses:
const parens = rregex('g')`\(
( [^\(\)] | (?R=10) )*
\)`;
'test (balanced ((parens))) ) () ((a)) ((b)'.match(parens);
Match palindromes:
const palindromes = rregex('gi')`(?<char>\w) ((?R=10)|\w?) \k<char>`;
'Racecar, ABBA, and redivided'.match(palindromes);
Match palindromes as complete words:
const palindromeWords = rregex('gi')`
\b
(?<palindrome>
(?<char>\w)
# Recurse, or match a lone unbalanced char in the center
( \g<palindrome&R=10> | \w? )
\k<char>
)
\b
`;
'Racecar, ABBA, and redivided'.match(palindromeWords);
Sugar free
Template tag rregex
is sugar for applying recursion support via a postprocessor with tag regex
. You can also add recursion support the verbose way:
import {regex} from 'regex';
import {recursion} from 'regex-recursion';
regex({flags: 'g', postprocessors: [recursion]})`a(?R=2)?b`;
Install and use
npm install regex-recursion
import {rregex} from 'regex-recursion';
In browsers:
<script src="https://cdn.jsdelivr.net/npm/regex-recursion/dist/regex-recursion.min.js"></script>
<script>
const {rregex} = Regex.ext;
</script>