ESC
Type to search...
S
Soli Docs

Regex Class

Regular expression matching, finding, replacing, splitting, and capturing via the Regex class.

Tip: Use raw strings (e.g., r"\d+") for regex patterns to avoid escaping backslashes.

Pattern Matching

Regex.matches(pattern, string)

Test if a string matches a regex pattern.

Returns

Bool - true if the pattern matches, false otherwise
Regex.matches(r"^[a-z]+$", "hello")  # true
Regex.matches(r"^[0-9]+$", "hello")  # false
Regex.matches(r"\d{3}-\d{4}", "555-1234")  # true
Regex.find(pattern, string)

Find the first match in a string.

Returns

Hash? - { "match": String, "start": Int, "end": Int } or null if no match
let result = Regex.find(r"[0-9]+", "abc123def")
println(result["match"])  # "123"
println(result["start"])  # 3
println(result["end"])    # 6
Regex.find_all(pattern, string)

Find all matches in a string.

Returns

Array - Array of match objects
let all = Regex.find_all(r"[0-9]+", "a1b2c3")
# [{"match": "1", "start": 1, "end": 2},
#  {"match": "2", "start": 3, "end": 4},
#  {"match": "3", "start": 5, "end": 6}]

Replacing

Regex.replace(pattern, string, replacement)

Replace the first match.

Regex.replace(r"[0-9]+", "a1b2", "X")  # "aXb2"
Regex.replace_all(pattern, string, replacement)

Replace all matches.

Regex.replace_all(r"[0-9]+", "a1b2", "X")  # "aXbX"
string.gsub(pattern, replacement)

Replace all regex matches in a string (convenience method).

"hello 42 world 7".gsub(r"\d+", "X")  # "hello X world X"
"foo bar foo".gsub(r"foo", "baz")     # "baz bar baz"
string.sub(pattern, replacement)

Replace the first regex match in a string.

"hello 42 world 7".sub(r"\d+", "X")  # "hello X world 7"

Splitting & Capturing

Regex.split(pattern, string)

Split a string by a regex pattern.

Regex.split(r"[,;]", "a,b;c")  # ["a", "b", "c"]
Regex.split(r"\s+", "hello   world")  # ["hello", "world"]
Regex.capture(pattern, string)

Capture named groups from a pattern.

let result = Regex.capture(
    r"(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})",
    "2024-01-15"
)
println(result["year"])   # "2024"
println(result["month"])  # "01"
println(result["day"])    # "15"
Regex.escape(string)

Escape special regex characters in a string.

Regex.escape("hello.world")  # "hello\\.world"
Regex.escape("(test)")       # "\\(test\\)"