Regex are very cool. Regexes, also known as regular expressions, are a powerful tool for matching patterns in text. Swift supports several ways to create a regular expression, including from a string, as a literal, and using this DSL.
‘Regex’ type, is a new type in the Swift Standard Library. A language built-in Regex literal syntax, which makes this powerful and familiar concept. And finally, a result builder API called RegexBuilder. It is a domain-specific language, or DSL.
Here I’ll discuss about above 3 ways to create regex:
- Regex from String
- Regex as literal
- Regex by Builder api
Lets start with an example — I have a string which contains some hashtags. Now I’ll create regex to find all the hashtags from the string.
let text = "My #name is #sanjeev and I am an #engineer with #10 years of #experience. Currently, working on #apple #technology."
1. Regex from String
Regex is a structure which represents a string processing algorithm.
In the above code, I have created Regex by the string (“#[a-z0–9]+”). This string format is very simple just tells to count the words which start from alphabet or number with ‘#’ symbol as prefix. Then getting all the matches from the string. After that displayed the matched word by the regex range.
2. Regex as literal
Now tried the same example with the literal approach. It is almost same as first approach except one thing — regex declaration.
Here, regex is declared as the literal statement. Expression is formatted within the two forward slashes like this (/../).
3. Regex by Regex Builder Api
Regex builder use an expressive domain-specific language to build regular expressions.
Convert regex literal into regex builder automatically
Xcode provides an option to convert regex literal statement into regex builder automatically. Just do right click on literal statment and goto Refacter. There is an option “Convert to Regex Builder”.
You can see that regex literal is replaced by a regex closure of builder api. It contains some components & quantifiers of builder api. First is the ‘#’ which is prefix hard code text for hashtag. Second is the quantifire OneOrMore for one or more occurances of the defined characters. And finally third is the CharacterClass list of characters which needs to be match.
How to build Regex by Builder Api
You can directly create regex by builder api. Apple provides components, quantifiers, captures & builders to create regex. If we talk about the above example then here is the sample of regex by builder api —
You can see there is only one thing which is OneOrMore quantifier for matching the word. If you want to find something else then simply change the CharacterClass.
You can go through more about Regex Builder on Apple Document.
If you know about regular expressions then it is very easy to you create regex by builder api. Really, now Swift made it very cool.
Thank You. Happy coding! 👍
#wwdc2022 #wwdc22 #regex #swift #iOS #regexbuilder