Want to offer native, in-app customer service to your users? Get going quickly with Zendesk’s Mobile SDKs. Free with Zendesk.

Regular Expressions are a fantastic way to search through text. Apple provides support for them via the NSRegularExpression class. It has great support for matching, extracting, etc. Its API can be a bit verbose for simple matches though. Today we'll look at Regex, a tiny little library from Adam Sharp that makes writing regular expressions in Swift much more friendly and expressive. Let's check it out:

Regex has a bunch of great features, but at its core it allows us to take regular expression code like this:

let stringToMatch = "star wars"

let regex = try! NSRegularExpression(
  pattern: "star (wars|trek)",
  options: NSRegularExpressionOptions(rawValue: 0)

let isWarsOrTrek = regex.firstMatchInString(
  options: NSMatchingOptions(rawValue: 0),
  range: NSMakeRange(0, stringToMatch.characters.count)
) != nil

...and turn it into something just a tad more readable:

Regex("star (wars|trek)").matches(stringToMatch)

Regex is backed by NSRegularExpression under the hood, and it does a great job of "swift-ifying" its API. In addition to simple Boolean checks, we can also use Regex in a few other rather Swifty ways. For example, pattern matching:

switch starThing {
case Regex("gate$"): print("dial the gate!")
case Regex("wars$"): print("the force is strong")
case Regex("trek$"): print("set phasers to stun")
default: break

Last but not least, we can easily grab any captured strings:

let starRegex = Regex("star( trek| wars|gate)")
if let captured = starRegex.match(inputString)?.captures.first {
  print("You chose: \(captured).")

More info about Regex can be found at git.io/regex