Regular expressions
Find, test, and replace text that matches a pattern.
On this page
valk.regex matches text against a pattern. Compile the pattern once with Regex.new, then use it as often as needed.
Find a match#
use valk.regex
fn main() {
let numbers = regex.Regex.new("\\d+") ! {
println("Invalid pattern")
return
}
let found = numbers.find("Order 42 shipped") ?! return
println(found.str()) // 42
}
find returns the first match or null. found.str() is the matched text, and found.start is its byte offset in the text. Inside a Valk string a backslash has to be doubled, so the pattern \d+ is written "\\d+".
Find every match, replace, or test#
use valk.regex
fn main() {
let words = regex.Regex.new("[a-z]+") ! return
each words.find_all("one two three") as found {
println(found.str())
}
let digits = regex.Regex.new("\\d") ! return
println(digits.replace("a1b2", "#")) // a#b#
println(digits.is_match("abc")) // false
}
find_all returns every match, replace substitutes them all, split breaks text at each match, and is_match only answers whether the pattern occurs.
Groups and flags#
Parentheses capture parts of a match: with the pattern (\w+)@(\w+), found.get(1) is the text before the @. Named groups, written (?P<user>\w+), are read with found.named("user").
Regex.new(pattern, "i") matches without regard to case. The other flags are m, which lets ^ and $ match at line boundaries, and s, which lets . match a newline.
Matching never backtracks, so a pattern from user input cannot make the program hang. Backreferences and lookaround are not supported.