• Stars
    star
    612
  • Rank 73,287 (Top 2 %)
  • Language
    Swift
  • License
    MIT License
  • Created about 9 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A delightful and expressive regular expression type for Swift.

Regex

Pattern match like a boss.

Usage

Create:

// 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)")
  }
}

Match:

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

Pattern match:

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

Capture:

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)!")
  }
default:
  break
}

Options:

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"]

Decode:

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!/)

Ranges:

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"]

Installation

Regex supports Swift 4.2 and above, on all Swift platforms.

Swift Package Manager

Add a dependency to your Package.swift:

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

Carthage

Put this in your Cartfile:

github "sharplet/Regex" ~> 2.1

CocoaPods

Put this in your Podfile:

pod "STRegex", "~> 2.1"

Contributing

See CONTRIBUTING.md.

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.

Xcode

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

Formatting & Linting

Regex uses SwiftFormat to maintain consistent code formatting.

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

When submitting a pull request, running these tools and addressing any issues is much appreciated!

brew bundle
swiftformat .
swiftlint

License

See LICENSE.txt.

More Repositories

1

EnumeratorKit

Ruby-style enumeration in Objective-C.
Objective-C
69
star
2

sigswift

A toy, event-driven command line app inspired by the Elm Architecture
Swift
20
star
3

swift-git

Swift bindings for libgit2.
Swift
18
star
4

SwiftIO

Simple Tools for File I/O in Swift
Swift
11
star
5

minimal-swift

Ruby
10
star
6

swiftags

Generate ctags for Swift projects using SourceKit.
Swift
10
star
7

State

An implementation of the State monad in Swift.
Swift
10
star
8

swift-cgit2

Swift package providing pre-built libgit2 binaries.
Shell
6
star
9

dotfiles

Vim Script
6
star
10

Swiftify

Swift
6
star
11

PublisherQueue

Model asynchronous tasks as publishers and limit concurrent execution
Swift
6
star
12

Anonymous

Objective-C
4
star
13

gift

Just make me a GIF already.
Swift
3
star
14

ReactiveMatchers

Nimble matchers for ReactiveCocoa
Swift
2
star
15

swift-git-example

Swift
2
star
16

carthage-without-xcode

Managing non-Cocoa dependencies with Carthage
Shell
2
star
17

trak

A command line tool for tracking chunks of time
Ruby
2
star
18

Prelude.swift

Swift + Haskell = Profit
Swift
2
star
19

HCIProject

A website for a HCI project
JavaScript
2
star
20

greetings-sqlite

Playing around with SQLite in Swift
Swift
2
star
21

Maelstrom

Type safe, expressive file operations in Swift.
Swift
2
star
22

rake-xcodebuild

Automate tedious and repetitive configuration of xcodebuild command line options.
Ruby
1
star
23

lightspeed

A lightweight build system for Swift.
Ruby
1
star
24

Temp.

The current temperature any way you want it.
Swift
1
star
25

thecodelesscode.com

HTML
1
star
26

hawk

Swift
1
star
27

tweetfree

A free software Twitter client
Objective-C
1
star
28

hack-swift

A suite of tools for the Hack computer platform written in Swift.
Assembly
1
star
29

five-day-plan

iOS app for tracking progress through the 5 Day Bible Reading Schedule
Swift
1
star