Regex class for Swift. Wraps NSRegularExpression.

Related tags

Text 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
Type strict builder class for NSAttributedString.

StringStylizer Type strict builder class for NSAttributedString. What's this? StringStylizer makes NSAttributedString more intuitive with Method chain

Kazuhiro Hayashi 75 Nov 11, 2022
BonMot is a Swift attributed string library

BonMot (pronounced Bon Mo, French for good word) is a Swift attributed string library. It abstracts away the complexities of the iOS, macOS, tvOS, and

Rightpoint 3.4k Dec 30, 2022
Croc is a swift emoji string parsing library

Croc is a library for parsing emojis on iOS. It provides a simple and lightweight interface for detecting, generating, categorizing and managing emoji characters, making emoji-powered features an easy task for developers.

Joe Kalash 127 Nov 20, 2022
Fully open source text editor for iOS written in Swift.

Edhita Fully open source text editor for iOS written in Swift. http://edhita.bornneet.com/ What Edhita means? Edhita (Romaji) == エディタ (Katakana) == Ed

Tatsuya Tobioka 1.2k Jan 1, 2023
A simple and customizable Markdown Parser for Swift

MarkdownKit MarkdownKit is a customizable and extensible Markdown parser for iOS and macOS. It supports many of the standard Markdown elements through

Bruno Oliveira 687 Dec 18, 2022
Marky Mark is a parser written in Swift that converts markdown into native views.

Marky Mark is a parser written in Swift that converts markdown into native views. The way it looks it highly customizable and the supported markdown syntax is easy to extend.

M2mobi 287 Nov 29, 2022
Swift Parser Combinators

Parsey Swift Parser Combinator Framework In addition to simple combinators, Parsey supports source location/range tracking, backtracking prevention, a

Richard Wei 56 Jun 30, 2022
Great Swift String Pluralize Extension

Pluralize.swift Great Swift String Pluralize Extension case-insensitive tons of rules for irregular nouns (plural form) supports uncountable nouns all

Joshua Arvin Lat 193 Nov 8, 2022
An NSPredicate DSL for iOS, OSX, tvOS, & watchOS. Inspired by SnapKit and lovingly written in Swift.

PrediKit A Swift NSPredicate DSL for iOS & OS X inspired by SnapKit, lovingly written in Swift, and created by that weird dude at KrakenDev. If you're

Hector Matos 542 Sep 24, 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
👩‍🎨 Elegant Attributed String composition in Swift sauce

Elegant Attributed String composition in Swift sauce SwiftRichString is a lightweight library which allows to create and manipulate attributed strings

Daniele Margutti 2.9k Jan 5, 2023
SwiftVerbalExpressions is a Swift library that helps to construct difficult regular expressions

SwiftVerbalExpressions Swift Regular Expressions made easy SwiftVerbalExpressions is a Swift library that helps to construct difficult regular express

null 582 Jun 29, 2022
A Swift framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber.

PhoneNumberKit Swift 5.3 framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber. Features F

Roy Marmelstein 4.7k Jan 8, 2023
A comprehensive, lightweight string extension for Swift

SwiftString SwiftString is a lightweight string extension for Swift. This library was motivated by having to search StackOverflow for common string op

Andrew Mayne 1.6k Dec 30, 2022
A Swift Formatter Kit

Format A Swift formatter kit. Simple formatting syntax for decimal numbers, currency, mass, addresses, ordinal numbers and hexadecimal colors. Usage I

Roy Marmelstein 1.2k Nov 8, 2022
🌭 Mustard is a Swift library for tokenizing strings when splitting by whitespace doesn't cut it.

Mustard ?? Mustard is a Swift library for tokenizing strings when splitting by whitespace doesn't cut it. Quick start using character sets Foundation

Mathew Sanders 695 Nov 11, 2022
Automatic summarizer text in Swift

Overview Reductio is a tool used to extract keywords and phrases using an implementation of the algorithm TextRank. Installation Swift Package Manager

Sergio Fernández 438 Dec 9, 2022
OysterKit is a framework that provides a native Swift scanning, lexical analysis, and parsing capabilities. In addition it provides a language that can be used to rapidly define the rules used by OysterKit called STLR

OysterKit A Swift Framework for Tokenizing, Parsing, and Interpreting Languages OysterKit enables native Swift scanning, lexical analysis, and parsing

Swift Studies 178 Sep 16, 2022
Swift markdown library

Markdown ![Swift version](https://img.shields.io/badge/Swift-2.1 | 2.2-blue.svg) ![GitHub license](https://img.shields.io/badge/license-LGPL v3-green.

Crossroad Labs 79 Oct 9, 2022