Swift 5.7's Regex Builder for email validation

103 views Asked by At

I have the following reg ex pattern to validate the email address with max length of 100 characters: (?=^.{0,100}$)([A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$)

I'm struggling to convert this pattern to the Swift 5.7's Regex builder DSL syntax, I I couldn't find a clue for how to convert it the correct way, however, the option in Xcode editor: (select the string pattern -> right-click -> Refactor -> Convert to Regex Builder) is disabled for no obvious reason.

1

There are 1 answers

1
Mojtaba Hosseini On

First you need to make it regex by surrounding it with / like:

let regex = /(?=^.{0,100}$)([A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$)/

Then you can use the Xcode's refactor feature to convert it to regex builder with one click:

Demo

let regex = Regex {
    Lookahead {
        Regex {
            /^/
            Repeat(0...100) {
                /./
            }
            /$/
        }
    }
    Capture {
        Regex {
            OneOrMore {
                CharacterClass(
                    .anyOf("._%+-"),
                    ("A"..."Z"),
                    ("0"..."9"),
                    ("a"..."z")
                )
            }
            "@"
            OneOrMore {
                CharacterClass(
                    .anyOf(".-"),
                    ("A"..."Z"),
                    ("a"..."z"),
                    ("0"..."9")
                )
            }
            "\\"
            /./
            Repeat(2...4) {
                CharacterClass(
                    ("A"..."Z"),
                    ("a"..."z")
                )
            }
            /$/
        }
    }
}