Hello, my fellow friends, Leo here. Today we’ll see how it can be easy to use regular expressions (RegEx) for pattern matching in Swift.

Regex is a very useful tool with you need more advanced pattern matching and it’s crucial 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 to do a simple assert with regex, it can be very simple and it’s what we are gonna explore today!

No more talking, let’s code!

 

Regex in Swift

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 to explain how to write regex, so you have a lot of tutorial options in google.

The focus here is to present a simple way to use regex swiftly. Regex is a very powerful tool.

Let’s code!

 

The Problem

You have to check 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!")
}

Explaining the comment numbers:

  1.  We start an 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 these steps too complex (and kinda are), 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.

 

Summary

Regex is a world “per se” and you must really dive into 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.

That’s all my people, I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or leave a comment saying hello. You can also sponsor posts and I’m open to freelance writing! You can reach me on LinkedIn or Twitter and send me an e-mail through the contact page.

Thanks for the reading and… That’s all folks.

Credits – image