Regular expressions are enclosed in matching pound sign (#
) characters with a prepended re
: re#...#
. KRL regular expressions follow the JavaScript standard, which closely follows the conventions for Perl regular expressions. The following modifiers may appear after the closing character:
i
. The i modifier makes the regular expression case insensitive.g
. The g modifier applies the regular expression globally.
For example, the following code replaces the first instance of foo
in p
with bar
:
p.replace(re#foo#, "bar")
In contrast, the following code replaces all instances of foo
in p
with bar
:
p.replace(re#foo#g, "bar")
Special characters
Like strings, the only special character is #
. To use a pound sign inside a regular expression, escape it with a backslash:
re#\##
A newline (\n) requires a line break:
re# #
Other characters can be inserted literally, although some text editors are better at this than others.
Rationale
KRL uses the hash character to delimit regular expressions instead of the more common (and acceptable) slash (/
) because the slash is a frequently used character in URL paths. This removes the need to quote the slash with backslashes: re/\/archives\/\d{4}\//
. Using an alternate delimiter makes the regex more readable and thus communicates its meaning more clearly.
Issues
- Escaping backslashes: https://github.com/Picolab/pico-engine/issues/284