Regex class for Swift. Wraps NSRegularExpression.

Related tags

Regex Regex
Overview

Regex.swift

Build Status CocoaPods CocoaPods CocoaPods GitHub tag

install

Use CocoaPods.

Add to your Podfile:

pod 'Regex'

And then run pod install from the shell:

$ pod install

usage

Simple use cases: String extension methods

String.grep()

This method is modeled after Javascript's String.match(). It returns a Regex.MatchResult object. The object's captures property is an array of Strings much as one would expect from its Javascript equivalent.

let result = "Winnie the Pooh".grep("\\s+([a-z]+)\\s+")

result.searchString == "Winnie the Pooh"
result.captures.count == 2
result.captures[0] == " the "
result.captures[1] == "the"
result.boolValue == true       // `boolValue` is `true` if there were more than 0 matches

// You can use `grep()` in conditionals because of the `boolValue` property its result exposes
let emailAddress = "bryn&typos.org"
if !emailAddress.grep("@") {
    // that's not an email address!
}

String.replaceRegex()

This method is modeled after the version of Javascript's String.replace() that accepts a Regex parameter.

let name = "Winnie the Pooh"
let darkName = name.replaceRegex("Winnie the ([a-zA-Z]+)", with: "Darth $1")
// darkName == "Darth Pooh"

Advanced use cases: Regex object and operators

operator =~

You can use the =~ operator to search a String (the left operand) for a Regex (the right operand). It's the same as calling theString.grep("the regex pattern"), but might be more clear in some cases. It returns the same Regex.MatchResult object as String.grep().

"Winnie the Pooh" =~ Regex("\\s+(the)\\s+")  // returns a Regex.MatchResult

Quickly loop over a Regex's captures:

for capture in ("Winnie the Pooh" =~ Regex("\\s+(the)\\s+")).captures {
    // capture is a String
}

Overriden map() function for substitution

A more "functional programming" way of doing string replacement is possible via an override for map(). In keeping with the overall aim to avoid reinventing a perfectly good wheel (i.e., NSRegularExpression), this function simply calls through to NSRegularExpression.replaceMatchesInString().

func map (regexResult:Regex.MatchResult, replacementTemplate:String) -> String

You can use it like so:

let stageName = map("Winnie the Pooh" =~ Regex("([a-zA-Z]+)\\s+(the)(.*)"), "$2 $1")
// stageName == "the Winnie"

Or if you have some functional operators lying around (for example: https://github.com/brynbellomy/Funky), it's a little less wordy:

("Winnie the Pooh" =~ Regex("([a-zA-Z]+)\\s+(the)(.*)")) |> map("$2 $1")

... but you have to be as crazy as me to find that more readable than "Winnie".replaceRegex(_:withString:), so no pressure.

contributors / authors

Comments
  • Convert to Swift 2

    Convert to Swift 2

    This is a fairly naive conversion to Swift 2 syntax, using the automatic conversion tool in the Xcode 7 beta and then manually fixing a couple of issues. It seems to pass the test suite, so hopefully it's basically correct.

    opened by nbudin 3
  • Title string and views are becoming blurry when it runs in non-plus devices

    Title string and views are becoming blurry when it runs in non-plus devices

    HELLO,your work was great! And I find when I triger the animation, titles and views are becoming blurry when it runs in non-plus devices, how can I fix this?

    opened by Longroader 0
  • Updated to Swift 3.1/XCode8.3.3

    Updated to Swift 3.1/XCode8.3.3

    Swift 2 project was auto updated by XCode and I made some tweaks to get it to compile. It ran the tests correctly, but I should probably find a nice regex test suite.

    opened by ghost 0
  • changed property

    changed property "Regex.MatchResult.captures" type from String array to String optional array ([String?])

    Needed for more complex regular expressions where NSRegularExpression returns NSRange with location == NSNotFound.

    Example: let regex = Regex("([a-z]+)(.([a-z]+))?.([a-z]+)") let result = regex.match("abcd.abcd")

    Expected result is ["abcd", nil, nil, "abcd"] but it throws an exception in current version

    String.match() in JavaScript has the same behaviour.

    opened by ondrejstocek 0
  • Manual Installation

    Manual Installation

    CocoaPods and Carthage are awesome tools and make our life really easier, but there are some devs who still don't know how to use them.

    It would be cool to add the Manual installation guide in your README.md. You can take a look at my iOS Readme Template to see how you can do it.

    opened by lfarah 0
Owner
Bryn Bellomy
Distributed systems, P2P
Bryn Bellomy
Easily deal with Regex in Swift in a Pythonic way

PySwiftyRegex Easily deal with Regex in Swift in a Pythonic way. 简体中文 日本語 한국어 This is Easy import PySwiftyRegex if let m = re.search("[Tt]his is (.*?

Ce Zheng 232 Oct 12, 2022
Learn about how SoulverCore can give Swift "better than regex" data parsing features (for many common tasks)

String Parsing with Soulver Core A declarative & type-safe approach to parsing data from strings SoulverCore gives you human-friendly, type-safe & per

Soulver 140 Nov 23, 2022
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|univ

Adam Sharp 612 Dec 17, 2022
Regular expressions for swift

Regex Advanced regular expressions for Swift Goals Regex library was mainly introduced to fulfill the needs of Swift Express - web application server

Crossroad Labs 328 Nov 20, 2022
This is a repo for my implementation of Gang of Four Book: Software Design Patterns. All written in Swift.

GoF-Swift-Design-Patterns This repo is intended to implement the known Software Design Patterns from the Gang of Four book using Swift Programming Lan

Noor El-Din Walid 3 Jul 11, 2022
XRepository: lightweight implementation of Repository pattern in Swift

XRepository is based on QBRepository by QuickBirds Studios. It is lightweight im

Sashko Potapov 2 Jan 10, 2022
Specification pattern implemented in swift (iOS/OSX)

SpecificationPattern The Specification design pattern implemented in swift for iOS/OSX. In computer programming, the specification pattern is a partic

Simon Strandgaard 46 Sep 21, 2022
Regex class for Swift. Wraps NSRegularExpression.

Regex.swift install Use CocoaPods. Add to your Podfile: pod 'Regex' And then run pod install from the shell: $ pod install usage Simple use cases: Str

Bryn Bellomy 67 Sep 14, 2022
A simple class that wraps the process of saving or loading a struct or class into a single file

EZFile This is a simple class that wraps the process of saving or loading a stru

null 7 May 16, 2022
PySwiftyRegex - Easily deal with Regex in Swift in a Pythonic way

PySwiftyRegex Easily deal with Regex in Swift in a Pythonic way.

Ce Zheng 232 Oct 12, 2022
Perl-like regex =~ operator for Swift

SwiftRegex Perl-like regex =~ operator for Swift This package implements a =~ string infix operator for use in testing regular expressions and retriev

Gregory Todd Williams 112 Oct 15, 2022
Easily deal with Regex in Swift in a Pythonic way

PySwiftyRegex Easily deal with Regex in Swift in a Pythonic way. 简体中文 日本語 한국어 This is Easy import PySwiftyRegex if let m = re.search("[Tt]his is (.*?

Ce Zheng 232 Oct 12, 2022
Learn about how SoulverCore can give Swift "better than regex" data parsing features (for many common tasks)

String Parsing with Soulver Core A declarative & type-safe approach to parsing data from strings SoulverCore gives you human-friendly, type-safe & per

Soulver 140 Nov 23, 2022
A Swift framework that wraps CoreData, hides context complexity, and helps facilitate best practices.

Cadmium is a Core Data framework for Swift that enforces best practices and raises exceptions for common Core Data pitfalls exactly where you make the

Jason Fieldman 123 Oct 18, 2022
A Swift framework that wraps CoreData, hides context complexity, and helps facilitate best practices.

Cadmium is a Core Data framework for Swift that enforces best practices and raises exceptions for common Core Data pitfalls exactly where you make them.

Jason Fieldman 123 Oct 18, 2022
CompositionalLayoutDSL, library to simplify the creation of UICollectionViewCompositionalLayout. It wraps the UIKit API and makes the code shorter and easier to read.

CompositionalLayoutDSL CompositionalLayoutDSL is a Swift library. It makes easier to create compositional layout for collection view. Requirements Doc

FABERNOVEL 44 Dec 27, 2022
Elegant library that wraps working with frames with a nice chaining syntax.

Everyone wants to see smooth scrolling, that tableview or collectionview scrolls without any lags and it's right choice. But the constraints do not gi

Nikita Ermolenko 133 Oct 9, 2022
A fast, convenient and nonintrusive conversion framework between JSON and model. Your model class doesn't need to extend any base class. You don't need to modify any model file.

MJExtension A fast, convenient and nonintrusive conversion framework between JSON and model. 转换速度快、使用简单方便的字典转模型框架 ?? ✍??Release Notes: more details Co

M了个J 8.5k Jan 3, 2023
Xcode Plugin helps you find missing methods in your class header, protocols, and super class, also makes fast inserting.

FastStub-Xcode Life is short, why waste it on meaningless typing? What is it? A code generating feature borrowed from Android Studio. FastStub automat

mrpeak 509 Jun 29, 2022
MisterFusion is Swift DSL for AutoLayout. It is the extremely clear, but concise syntax, in addition, can be used in both Swift and Objective-C. Support Safe Area and Size Class.

MisterFusion MisterFusion makes more easier to use AutoLayout in Swift & Objective-C code. Features Simple And Concise Syntax Use in Swift and Objecti

Taiki Suzuki 316 Nov 17, 2022