Swiftpack.co - Package - sharplet/Regex


Pattern match like a boss.



// Use `Regex.init(_:)` to build a regex from a static pattern

let greeting = Regex("hello (world|universe)")

// Use `Regex.init(string:)` to construct a regex from dynamic data, and
// gracefully handle invalid input

var validations: [String: Regex]

for (name, pattern) in config.loadValidations() {
  do {
    validations[name] = try Regex(string: pattern)
  } catch {
    print("error building validation \(name): \(error)")


if greeting.matches("hello universe!") {
  print("wow, you're friendly!")

Pattern match:

switch someTextFromTheInternet {
case Regex("DROP DATABASE (.+)"):
  // TODO: patch security hole


let greeting = Regex("hello (world|universe|swift)")

if let subject = greeting.firstMatch(in: "hello swift")?.captures[0] {
  print("ohai \(subject)")

Find and replace:

"hello world".replacingFirst(matching: "h(ello) (\\w+)", with: "H$1, $2!")
// "Hello, world!"

Accessing the last match:

switch text {
case Regex("hello (\\w+)"):
  if let friend = Regex.lastMatch?.captures[0] {
    print("lovely to meet you, \(friend)!")
case Regex("goodbye (\\w+)"):
  if let traitor = Regex.lastMatch?.captures[0] {
    print("so sorry to see you go, \(traitor)!")


let totallyUniqueExamples = Regex("^(hello|foo).*$", options: [.ignoreCase, .anchorsMatchLines])
let multilineText = "hello world\ngoodbye world\nFOOBAR\n"
let matchingLines = totallyUniqueExamples.allMatches(in: multilineText).map { $0.matchedString }
// ["hello world", "FOOBAR"]


let json = """
      "name" : "greeting",
      "pattern" : "^(\\\\w+) world!$"
  """.data(using: .utf8)!

struct Validation: Codable {
  var name: String
  var pattern: Regex

let decoder = JSONDecoder()
try decoder.decode(Validation.self, from: json)
// Validation(name: "greeting", pattern: /^(\w+) world!/)


let lyrics = """
  So it's gonna be forever
  Or it's gonna go down in flames

let possibleEndings = Regex("it's gonna (.+)")
    .allMatches(in: lyrics)
    .flatMap { $0.captureRanges[0] }
    .map { lyrics[$0] }

// it's gonna: ["be forever", "go down in flames"]


Swift Package Manager

Add a dependency to your Package.swift:

// Swift 4

let package = Package(
  name: "MyPackage",
  dependencies: [
    // other dependencies...
    .package(url: "https://github.com/sharplet/Regex.git", from: "1.1.0"),
// Swift 3

let package = Package(
  name: "MyPackage",
  dependencies: [
    // other dependencies...
    .Package(url: "https://github.com/sharplet/Regex.git", majorVersion: 1, minor: 1),


Put this in your Cartfile:

github "sharplet/Regex" ~> 1.1


Put this in your Podfile:

pod "STRegex", "~> 1.1"



Development Setup

Swift Package Manager

Build and run the tests:

swift test

# or just

rake test:package

If you're on a Mac, testing on Linux is supported via Docker for Mac. Once Docker is set up, start a Linux shell:

rake docker

And run the tests via Swift Package Manager.

Carthage & Xcode

Install Carthage via Homebrew and build the dependencies:

brew install carthage
rake setup

xcpretty is recommended, for prettifying test output:

gem install xcpretty

Then run the tests:

# one of
rake test:osx
rake test:ios
rake test:tvos


Regex uses SwiftLint to validate code style. SwiftLint is automatically run against pull requests using Hound CI.

You can also run it locally:

$ brew install swiftlint
$ rake swiftlint


See LICENSE.txt.


Stars: 497
Help us keep the lights on



1.1.0 - Aug 4, 2017

Regex now speaks Swift 4! 🎉


  • The Regex type now conforms to Codable, so you can encode and decode regular expressions to your heart's content. (#52)
  • MatchResult has a new range property. (#54, thanks @mezhevikin!)
  • To go with MatchResult.range, there's also the captureRanges property, allowing you to work with the ranges of capture groups. (#59)


  • Regex now handles the newly overhauled String index API, maintaining that sweet, sweet Unicode correctness, whatever your chosen Swift version. (#57, 7952baebc8cf08597c2810496b7e777e6212be00, 1a90514f101436f8f92f06e4c5796e8e58458285, thanks @wspl!)

Thanks for using Regex!

1.0.0 - Jun 13, 2017

Regex is now officially at 1.0.0! 🎉

Here's a quick hit list of features:

  • Easily and safely create regular expressions
  • When creating a regular expression from a static string, no error handling required
  • Great pattern-matching support via Regex.lastMatch
  • Type safe access to capture groups
  • Convenient extensions to String to support find and replace

I hope you enjoy using Regex!

0.4.3 - Dec 12, 2016

Fixes a build failure when using Swift Package Manager.

0.4.2 - Sep 25, 2016

This should add full Swift 3 support for swiftpm and CocoaPods users. Carthage users should be able to opt into Swift 3 using the --toolchain option to carthage build.

Breaking changes to drop Swift 2 support and adopt the Swift API Design Guidelines will be made in a future release.

0.4.1 - Sep 15, 2016


  • New DotMatchesLineSeparator option allows . to match new line characters such as \n. Thanks @ninjaprawn!