---
title: "#121: Swiftier Regular Expressions with Regex 🔍📖"
url: https://littlebitesofcocoa.com/121-swiftier-regular-expressions-with-regex
author: Jake Marsh
published: 2015-11-09
topics: ["Foundation","Libraries"]
description: "Regular Expressions are a fantastic way to search through text. Apple provides support for them via the NSRegularExpression class."
---

# #121: Swiftier Regular Expressions with Regex 🔍📖

By Jake Marsh, November 9, 2015. HTML: https://littlebitesofcocoa.com/121-swiftier-regular-expressions-with-regex

_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](http://git.io/regex), a tiny little library from [Adam Sharp](https://github.com/sharplet) that makes writing _regular expressions_ in **Swift** much more friendly and expressive. Let's check it out:

[Regex](http://git.io/regex) has a bunch of great features, but at its core it allows us to take _regular expression_ code like this:

``` swift
let stringToMatch = "star wars"

let regex = try! NSRegularExpression(
  pattern: "star (wars|trek)",
  options: NSRegularExpressionOptions(rawValue: 0)
)

let isWarsOrTrek = regex.firstMatchInString(
  stringToMatch,
  options: NSMatchingOptions(rawValue: 0),
  range: NSMakeRange(0, stringToMatch.characters.count)
) != nil
```

...and turn it into something just a <i>tad</i> more readable:

``` swift
Regex("star (wars|trek)").matches(stringToMatch)
```

[Regex](http://git.io/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](http://git.io/regex) in a few other rather <i>Swifty</i> ways. For example, **pattern matching**:

``` swift
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**:

``` swift
let starRegex = Regex("star( trek| wars|gate)")
if let captured = starRegex.match(inputString)?.captures.first {
  print("You chose: \(captured).")
}
```

More info about [Regex](http://git.io/regex) can be found at [git.io/regex](http://git.io/regex)
