1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
regex: regular expressions
The regex module provides an implementation of regular expressions which adheres
closely to the POSIX Extended Regular Expressions (ERE) specification.
See https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04
This module refers to a regular expression "match" as a [[result]]. The POSIX
match disambiguation rules are used; the longest of the leftmost matches is
returned. This implementation computes matches in linear time.
Compiling an expression:
const re = regex::compile(`[Hh]a(rriet|ppy)`)!;
defer regex::finish(&re);
Testing an expression against a string:
assert(regex::test(&re, "Harriet is happy"));
Finding a match for an expression in a string:
const result = regex::find(&re, "Harriet is happy");
defer regex::result_free(result);
for (let i = 0z; i < len(result); i += 1) {
fmt::printf("{} ", result[i].content)!;
};
fmt::println()!;
// -> Harriet rriet
Finding all matches for an expression in a string:
const results = regex::findall(&re, "Harriet is happy");
defer regex::result_freeall(results);
for (let i = 0z; i < len(results); i += 1) {
for (let j = 0z; j < len(results[i]); j += 1) {
fmt::printf("{} ", results[i][j].content)!;
};
fmt::println()!;
};
// -> Harriet rriet; happy ppy
Replacing matches for an expression:
const re = regex::compile(`happy`)!;
const result = regex::replace(&re, "Harriet is happy", `cute`)!;
// -> Harriet is cute
Replacing with capture group references:
const re = regex::compile(`[a-z]+-([a-z]+)-[a-z]+`)!;
const result = regex::replace(&re, "cat-dog-mouse; apple-pear-plum",
`\1`)!;
// -> dog; pear
|