Skip to main content

Regex

Search and replace text with regular expressions
]help •r

•r — Regular expressions

text •r pattern gives a table of the matches of the regular expression pattern in text, as a record of columns: text, the matched text; position, its position in characters from 0; and groups, the text of each group, which is empty for a group that took no part. •replace replaces matches. BPL keeps the 16 patterns it compiled last, so a loop that uses one pattern compiles it once.

Natively the pattern uses fancy-regex’s syntax, including lookaround and backreferences. Put flags in the pattern, as in (?i). A search that exceeds the engine’s backtracking limit raises DOMAIN. In the browser the pattern is a JavaScript regular expression, with JavaScript’s syntax. Regular expressions covers matching and replacing.

"ab12 cd3" •r "([a-z]+)([0-9]+)"   ⍝ ["text":["ab12" "cd3"] "position":[0 5]ₓ "groups":("ab" "12"◇"cd" "3")]

Errors: DOMAIN for invalid patterns and non-text arguments; SYNTAX for the wrong valence; LIMIT for oversized results.

Natively, patterns use fancy-regex syntax, including lookaround and backreferences. Exceeding the engine’s backtracking limit raises DOMAIN. In the browser, patterns use JavaScript’s regular expression syntax. text •r pattern gives a table of the matches, as a record of columns. This pattern finds runs of digits:

"abc123def45" •r "[0-9]+"
["text":["123" "45"] "position":[3 9]ₓ "groups":[0ρ⊂"" 0ρ⊂""]]

Matches don’t overlap. The position column counts characters, and ≢¨ of the text column gives each match’s length. For a text with no match, •r gives a table with no rows:

m←"aé🐈🐈z" •r "é|🐈+"
m.position
≢¨m.text
"abc" •r "é|🐈+"
[1 2]ₓ
[1 2]ₓ
["text":0ρ⊂"" "position":⍬ₓ "groups":0ρ⊂0ρ⊂""]

The groups column holds the captured strings of each match, without the whole match. For an unmatched optional capture, groups holds "":

("ab12 cd3" •r "([a-z]+)([0-9]+)").groups
("ab" "12"◇"cd" "3")

text •replace [pattern template] replaces each match of pattern with template. In a native template, $0 is the whole match and $$ is a literal $. An unknown or unmatched capture expands to "". In the browser, templates use JavaScript’s syntax, where $<word> refers to the group named word:

"ab12" •replace ["(?P<word>[a-z]+)([0-9]+)" "${word}:$2:$$"]
"ab:12:$"

Natively, inline flags change how a pattern matches. (?i) ignores case. (?m) makes ^ and $ match at each line break. (?s) makes . match line breaks too. Use ¨ to search several strings:

{≢(ω •r "(?i)cat").text}¨"Cat cat" "dog"
[2 0]ₓ

Empty matches occur at character boundaries:

("é🐈" •r "").position
"é🐈" •replace ["" "-"]
[0 1 2]ₓ
"-é-🐈-"

lib/regex.bpl supplies pattern f regex_replace text. It applies f to each matched string and keeps the text between matches:

[regex_replace:]←•load "../lib/regex.bpl"
"[0-9]+" {⍕⊽•jsonω}regex_replace "a12 b3"
"a24ₓ b6ₓ"