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