I was wondering if it would be possible to have named captures in Regex builders.
Presently I am able to access the match?.1 to get the capture value.
Is it possible to define a named capture so that I can instead use match?.greeting (instead of using .1)?
Note: I am new to regular expression and Swift Regex.
Code
let regex = Regex {
OneOrMore(.digit)
Capture {
OneOrMore {
CharacterClass(
("a"..."z"),
("A"..."Z")
)
}
}
}
let source = "123hello890"
let match = source.firstMatch(of: regex)
let a = match?.1 //Is it possible to have a named capture instead of using .1
Hello @somu! As you've noticed, RegexBuilder doesn't support named capture groups. Instead, you can create a Reference and use that to look up a capture after matching. References are strongly typed, so in your case, you'll create a Reference<Substring> called greeting, pass greeting when declaring your capture, and then use greeting in a subscript on the resulting match:
// create the 'greeting' reference
let greeting = Reference<Substring>()
let regex = Regex {
OneOrMore(.digit)
Capture(as: greeting) { // specify 'greeting' here
OneOrMore {
CharacterClass(
("a"..."z"),
("A"..."Z")
)
}
}
}
let source = "123hello890"
let match = source.firstMatch(of: regex)
let a = match?[greeting] // look up the captured value
let b = match?.1 // the previous syntax still works, as well