Regex
import "std/text" (included in import "std") · namespace std.text
Regular expressions: patterns that describe text, for searching, validating, extracting and replacing. Regex compiles a pattern once; then you can test strings against it, find matches and their capture groups, replace and split.
The syntax is POSIX extended regular expressions, from the C library:
| Pattern | Matches |
|---|---|
abc | the text abc |
. | any character |
[abc], [a-z], [^0-9] | one of the characters, a range, or anything but |
x*, x+, x? | zero or more, one or more, zero or one x |
x{3}, x{2,5} | exactly 3, or 2 to 5 x |
a|b | a or b |
( ... ) | a group, captured for group(n) and $n |
^, $ | the start and end of the text |
[[:digit:]], [[:alpha:]], [[:space:]], [[:alnum:]] | character classes |
In a Grav string, a backslash must itself be escaped ("\\."), or use a raw string: r"\.txt$".
Matching never changes a Regex: compile a pattern once and share it, even between threads matching at the same time.
import "std"
fn main() {
let date = new Regex("([0-9]{4})-([0-9]{2})-([0-9]{2})")
let m = date.find("due 2024-03-15!")
if (m != null) {
print("${m.text} at ${m.start}: year ${m.group(1)}")
}
print(date.replaceAll("2024-03-15 and 1999-12-31", "$3/$2/$1"))
let email = new Regex("^[^@ ]+@[^@ ]+\\.[a-z]+$", true)
print(email.matches("Ada@Example.com"))
print(email.matches("not an email"))
print(new Regex("[0-9]+").findAllText("a1 b22 c333"))
print(new Regex(r"\s*[,;]\s*").split("a , b;c ,d"))
print(new Regex("[aeiou]").replaceAllWith("banana", fn(x: RegexMatch) => Str.upper(x.text)))
print(Regex.escape("1+1=2?"))
}2024-03-15 at 4: year 2024
15/03/2024 and 31/12/1999
true
false
["1", "22", "333"]
["a", "b", "c", "d"]
bAnAnA
1\+1=2\?findreturnsnullwhen there is no match;matchesrequires the whole string to match,testany part of it.- In replacements,
$0is the whole match,$1to$9the groups,$$a dollar sign.replaceAllWithcomputes each replacement with a function. - A pattern can have at most 9 groups. Positions (
start,end) are byte offsets. - An invalid pattern throws
ValueErrorwith the C library's explanation. new Regex(pattern, true)ignores case.
API
class RegexMatch
One match: the matched text, where it is, and its capture groups.
Constructors
new RegexMatch(text: string, start: int, end: int, groups: Array<string>)
Fields
readonly text: string— The whole matched text.readonly start: int— Byte offset where the match starts.readonly end: int— Byte offset just after the match.
Methods
fn group(i: int) -> string— Capture group i (0 is the whole match); "" when the group did not take part. IndexError for a group the pattern does not have.fn groupCount() -> int— The number of capture groups in the pattern.fn groupList() -> Array<string>— Every capture group (not the whole match), in order.fn toString() -> string— As text: the matched text.
class Regex
A compiled regular expression (POSIX extended syntax).
Constructors
new Regex(pattern: string)— Compilespattern; ValueError when it is not a valid regular expression.new Regex(pattern: string, ignoreCase: bool)— Compilespattern, ignoring upper/lower case whenignoreCaseis true.
Static members
static fn escape(s: string) -> string—swith every character that is special in a pattern escaped, so it matches literally.
Fields
readonly pattern: string— The pattern as written.
Methods
fn test(s: string) -> bool— Whether the pattern matches somewhere ins.fn matches(s: string) -> bool— Whether the pattern matches the whole ofs.fn find(s: string) -> RegexMatch— The first match ins, or null.fn findFrom(s: string, from: int) -> RegexMatch— The first match at or after byte offsetfrom, or null.fn findAll(s: string) -> Array<RegexMatch>— Every non-overlapping match ins, left to right.fn findEach(s: string) -> RegexMatches— The matches insone at a time, found as the loop asks for them (a loop that stops early does not search the rest):for (m in re.findEach(text)).fn findAllText(s: string) -> Array<string>— The text of every match.fn count(s: string) -> int— The number of non-overlapping matches.fn replace(s: string, replacement: string) -> string—swith the first match replaced byreplacement, where $0 is the whole match, $1..$9 are groups and $$ is a dollar sign.fn replaceAll(s: string, replacement: string) -> string—swith every match replaced byreplacement($0, $1..$9, $$ as in replace).fn replaceAllWith(s: string, f: fn(RegexMatch) -> string) -> string—swith every match replaced by whatfreturns for it.fn split(s: string) -> Array<string>— The pieces ofsbetween matches.fn toString() -> string— As text: the pattern.
class RegexMatches implements Iterator<RegexMatch>
A regex's matches in a text, found one at a time (see Regex.findEach).
Constructors
new RegexMatches(re: Regex, s: string)
Methods
fn hasNext() -> boolfn next() -> RegexMatch