Grav v1.14.0

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:

PatternMatches
abcthe 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|ba 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.

grav
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?"))
}
Output
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\?
  • find returns null when there is no match; matches requires the whole string to match, test any part of it.
  • In replacements, $0 is the whole match, $1 to $9 the groups, $$ a dollar sign. replaceAllWith computes each replacement with a function.
  • A pattern can have at most 9 groups. Positions (start, end) are byte offsets.
  • An invalid pattern throws ValueError with 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) — Compiles pattern; ValueError when it is not a valid regular expression.
  • new Regex(pattern: string, ignoreCase: bool) — Compiles pattern, ignoring upper/lower case when ignoreCase is true.

Static members

  • static fn escape(s: string) -> string — s with 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 in s.
  • fn matches(s: string) -> bool — Whether the pattern matches the whole of s.
  • fn find(s: string) -> RegexMatch — The first match in s, or null.
  • fn findFrom(s: string, from: int) -> RegexMatch — The first match at or after byte offset from, or null.
  • fn findAll(s: string) -> Array<RegexMatch> — Every non-overlapping match in s, left to right.
  • fn findEach(s: string) -> RegexMatches — The matches in s one 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 — s with the first match replaced by replacement, where $0 is the whole match, $1..$9 are groups and $$ is a dollar sign.
  • fn replaceAll(s: string, replacement: string) -> string — s with every match replaced by replacement ($0, $1..$9, $$ as in replace).
  • fn replaceAllWith(s: string, f: fn(RegexMatch) -> string) -> string — s with every match replaced by what f returns for it.
  • fn split(s: string) -> Array<string> — The pieces of s between 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() -> bool
  • fn next() -> RegexMatch

Edit this page on GitHub