Transform Match with RegexBuilder
With RegexBuilder we are able to apply transformations to the matches that it finds, for example, if TryCapture is used rather than Capture then the whole match will fail if the capture fails. Let’s see how this works with the following code.
let str = "I am a dog who is 1 years old and my name is Luna"
let pattern = Regex {
"I am a "
Capture {
OneOrMore(.word)
}
" who is "
TryCapture {
OneOrMore(.digit)
} transform: { match in
Int(match)
}
" years old and my name is "
Capture {
OneOrMore(.word)
}
}
let matches = str.matches(of: pattern)
for match in matches {
print("-- \(str[match.range])")
}
In the Regex Builder code we are attempting to match a specific string with three string literals “I am a“, “who is“ and “years old and my name is“ and three capture blocks. The middle...