Swift 5.7 Regex and RegexBuilder

Hasancan Akgündüz
2 min readJun 25, 2022

--

Apple introduced RegexBuilder with Swift 5.7. It helps us create regexes to use in operations like searching a pattern in a text. I will demonstrate this with a task and its solution with RegexBuilder.

The task is to find all the words starting with vowel characters(a, e, i , o, u) in a sentence.

And here’s the solution with RegexBuilder:

Please check the regex variable. It is of type Regex and has been created by RegexBuilder.

Anchor.wordBoundary: With the help of this pre-defined regex component, we are able to find out that we are in the beginning of a new word.

One(.anyOf(“aeiou”)): In here, we make sure that we are expecting only one character matching any vowels.

ZeroOrMore { .word }: This quantifier helps us receive the remaining part of the word after vowel character. It is zero or more because we might have words with single vowel character like “a”.

run() function prints the matches found.

Converting old regex expressions

If you have a regex expression in your current project and want to convert it to regex builder, just right click on it and then go to refactor and tap on “Convert to Regex Builder” menu:

Here’s the conversion when you select it:

Thanks to Swift 5.7 RegexBuilder, now our new regex is easier to understand and maintain.…

--

--