Cross-platform Swift regex library


Build Status codecov Platform Language: Swift Carthage


If you are developing cross platform (macOS and Linux) command line apps, and you want to use Regular expressions, Regex is just what you need.

You can use Regex with Guaka to create aweseome command line applications.


  • Checking if a string matches a pattern.
let r = try! Regex(pattern: "Hello [a-z]+ame")
r.matches("Hello Name")
  • Capture a string with a regex capture group
let r = try! Regex(pattern: "Hello (.*) name")
let result = r.captures(string: "Hello mr name")

result is an array of CaptureResult

  • Using the ~= operator
// Regex ~= String
let value = try! Regex(pattern: "Hello [a-z]+ame") ~= "Hello Name"
// value is true

// String ~= Regex
let value = "Hello Name" ~= try! Regex(pattern: "Hello [a-z]+ame")
// value is true
  • Using regex matching with switch
switch "Hello I am on swift" {
  case try! Regex(pattern: "Hello [a-z] am .*"):
    // First
  case try! Regex(pattern: ".*"):
    // Second

The first passing regex will be matched. In the example above, the first case is matched.

String extensions

Replace a pattern with a string:

"This string is wrong".replacing(pattern: "w.*g", withString: "right")
// "This string is right"


CaptureResult represent a captured string, it contains:

  • originalString the original string
  • startIndex the capture start index
  • endIndex the capture end index
  • range the range of the captured string
  • string the captured string


RegexOptions optionset can be passed when initilaizing a Regex object. For a discussion on the meaning of these flags, refer to GNU regex documentation


matches(_:options:) accepts the MatchOptions option set. For a discussion on the meaning of these flags, refer to GNU regex documentation


You can install Regex using Swift package manager (SPM) and carthage

Swift Package Manager

Add Regex as dependency in your Package.swift

import PackageDescription

let package = Package(name: "YourPackage",
  dependencies: [
    .Package(url: "", majorVersion: 0),


github "getGuaka/Regex"


Tests can be found here.

Run them with

swift test


Just send a PR! We don't bite ;)


  • Swift Tools 4.0.0
View More Packages from this Author


  • None
Last updated: Mon Nov 07 2022 20:53:58 GMT-0500 (GMT-05:00)