Regular Expressions and Swift - The very minimum

Subscribe to my newsletter and never miss my upcoming articles

Hello my fellow friends, Leo here.

Today we'll see how can be easy use regular expressions (RegEx) for pattern matching in Swift. Regex a very useful tool with you need a more advanced pattern matching and it's very important to know the basics of the rules. I'll break the magic here for you all, Swift isn't the most straightforward language to do regex work, I mean, working with capturing groups is a LOT verbose. But if you want just do a simple assert with regex, it can be very simple and it's that what we are gonna explore today!

Theory

But what is regex ?

A regular expression (shortened as regex or regexp; also referred to as rational expression) is a sequence of characters that define a search pattern. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation. It is a technique developed in theoretical computer science and formal language theory. The concept arose in the 1950s when the American mathematician Stephen Cole Kleene formalized the description of a regular language. The concept came into common use with Unix text-processing utilities. Different syntaxes for writing regular expressions have existed since the 1980s, one being the POSIX standard and another, widely used, being the Perl syntax.

It's not the scope of this blog explaining how to write regex, for that you have a lot tutorial options in google . The focus here is just to present a simple way to use regex in swift. Regex is a very powerful tool

Let's code!

Problem

You have to check if the zip code from a text you received.

The code:

let testString = "09608-060"
let regexPattern = "\\d{5}-\\d{3}"

//1
let range = NSRange(location: 0, length: testString.count) // 1
let regexMatcher = try? NSRegularExpression(pattern: regexPattern) // 2
if regexMatcher?.firstMatch(in: testString, options: [], range: range) != nil { // 3
    print("regex match!")
}
  1. We start a NSRange with the size of the string, here you can also discard some part of the String if you already know it will be useless.
  2. After that you do the matcher injecting the regexPattern you want to check.
  3. You can check if inside that range you have a match for your String.

But if you find all this steps too much complex (and kinda is), you can resume all the steps with a single String extension:

extension String {
    func isMatchedBy(regex: String) -> Bool {
        return (self.range(of: regex, options: .regularExpression) ?? nil) != nil
    }
}

//and you can test like this
let testString2 = "carryon"
let regexPattern2 = ".*rr.*"

if(testString2.isMatchedBy(regex: regexPattern2)) {
    print("extesion works!")
}

The code inside the string extension style is the very minimum you can write in Swift to assert a regex. Tell me in the comment session if you find a shorter way to assert a simple regex in Swift.

Regex is a world 'per se' and you must really dive in to the topic to be really proficient. Moderate usage is recommended. I'll be writing more about regex in the future so stay tuned if you want this type of article.

Thanks for the reading and... That's all folks!

Credits: image

No Comments Yet