Regex Builder named capture

Hi,

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
1 Like

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
6 Likes

@nnnnnnnn Thank you so much!!!!

This makes the code much more readable, really helpful.

Really love using Regex and RegexBuilder, it makes regular expression a lot more accessible!

Thanks a lot to everyone who contributed to it, love it!.

3 Likes

Is there an easy way of declaring a regex and the capture group reference as a class property that could be accessed by multiple methods?

1 Like