Swifty regular expressions

Overview

Regex

Swifty regular expressions

This is a wrapper for NSRegularExpression that makes it more convenient and type-safe to use regular expressions in Swift.

Install

Add the following to Package.swift:

.package(url: "https://github.com/sindresorhus/Regex", from: "0.1.0")

Or add the package in Xcode.

Usage

First, import the package:

import Regex

Supported regex syntax.

Examples

Check if it matches:

true ">
Regex(#"\d+"#).isMatched(by: "123")
//=> true

Get first match:

"123" ">
Regex(#"\d+"#).firstMatch(in: "123-456")?.value
//=> "123"

Get all matches:

["123", "456"] ">
Regex(#"\d+"#).allMatches(in: "123-456").map(\.value)
//=> ["123", "456"]

Replacing first match:

"πŸ¦„456" ">
"123πŸ¦„456".replacingFirstMatch(of: #"\d+"#, with: "")
//=> "πŸ¦„456"

Replacing all matches:

"πŸ¦„" ">
"123πŸ¦„456".replacingAllMatches(of: #"\d+"#, with: "")
//=> "πŸ¦„"

Named capture groups:

[a-z]+)\d+"#) regex.firstMatch(in: "123unicorn456")?.group(named: "word")?.value //=> "unicorn" ">
let regex = Regex(#"\d+(?[a-z]+)\d+"#)

regex.firstMatch(in: "123unicorn456")?.group(named: "word")?.value
//=> "unicorn"

Pattern matching:

switch "foo123" {
case Regex(#"^foo\d+$"#):
	print("Match!")
default:
	break
}

switch Regex(#"^foo\d+$"#) {
case "foo123":
	print("Match!")
default:
	break
}

Multiline and comments:

true ">
let regex = Regex(
	#"""
	^
	[a-z]+  # Match the word
	\d+     # Match the number
	$
	"""#,
	options: .allowCommentsAndWhitespace
)

regex.isMatched(by: "foo123")
//=> true

API

See the API docs.

FAQ

Why are pattern strings wrapped in #?

Those are raw strings and they make it possible to, for example, use \d without having to escape the backslash.

Related

You might also like...
ΞΌ-library enabling if/else and switch statements to be used as expressions.

swift-expression Many languages such as Scala, Rust and Kotlin support using if/else and switch statements as expressions – meaning that they can by t

A cross-platform Swift library for evaluating mathematical expressions at runtime

Introduction What? Why? How? Usage Installation Integration Symbols Variables Operators Functions Arrays Performance Caching Optimization Standard Lib

Eval for Swift - Easily evaluate simple expressions on the go

Eval for Swift Easily evaluate simple expressions on the go... This is a port of the BigEval.js/Eval.net library Features: Evaluate basic math operato

Swifty and modern UserDefaults

Defaults Swifty and modern UserDefaults Store key-value pairs persistently across launches of your app. It uses NSUserDefaults underneath but exposes

The most swifty way to deal with XML data in swift 5.

SwiftyXML SwiftyXML use most swifty way to deal with XML data. Features Infinity subscript dynamicMemberLookup Support (use $ started string to subscr

A sweet and swifty YAML parser built on LibYAML.
A sweet and swifty YAML parser built on LibYAML.

Yams A sweet and swifty YAML parser built on LibYAML. Installation Building Yams requires Xcode 11.x or a Swift 5.1+ toolchain with the Swift Package

Swifty Date & Time API inspired from Java 8 DateTime API.

AnyDate Swifty Date & Time API inspired from Java 8 DateTime API. Background I think that date & time API should be easy and accurate. Previous dates,

A Swifty API for attributed strings

SwiftyAttributes A Swifty API for attributed strings. With SwiftyAttributes, you can create attributed strings like so: let fancyString = "Hello World

Fashion is your helper to share and reuse UI styles in a Swifty way.
Fashion is your helper to share and reuse UI styles in a Swifty way.

Fashion is your helper to share and reuse UI styles in a Swifty way. The main goal is not to style your native apps in CSS, but use a set

Swifty, modern UIAlertController wrapper.
Swifty, modern UIAlertController wrapper.

Alertift Alertift.alert(title: "Alertift", message: "Alertift is swifty, modern, and awesome UIAlertController wrapper.") .action(.default("❀️"))

🍞 Loaf is a Swifty Framework for Easy iOS Toasts
🍞 Loaf is a Swifty Framework for Easy iOS Toasts

Loaf 🍞 Inspired by Android's Toast, Loaf is a Swifty Framework for Easy iOS Toasts Usage From any view controller, a Loaf can be presented by calling

Swifty closures for UIKit and Foundation
Swifty closures for UIKit and Foundation

Closures is an iOS Framework that adds closure handlers to many of the popular UIKit and Foundation classes. Although this framework is a substitute f

A swifty iOS framework that allows developers to create beautiful onboarding experiences.
A swifty iOS framework that allows developers to create beautiful onboarding experiences.

SwiftyOnboard is being sponsored by the following tool; please help to support us by taking a look and signing up to a free trial SwiftyOnboard A simp

Swifty API for NSTimer

SwiftyTimer Modern Swifty API for NSTimer SwiftyTimer allows you to instantly schedule delays and repeating timers using convenient closure syntax. It

Swifty TVML template manager with or without client-server

TVMLKitchen πŸ˜‹ 🍴 TVMLKitchen helps to manage your TVML with or without additional client-server. Requirements Swift3.0 tvOS 9.0+ Use 0.9.6 for Swift2

Swifty and modern UserDefaults

Defaults Swifty and modern UserDefaults Store key-value pairs persistently across launches of your app. It uses NSUserDefaults underneath but exposes

A Swifty iOS PIN Screen
A Swifty iOS PIN Screen

SAPinViewController Simple and easy to use default iOS PIN screen. This simple library allows you to draw a fully customisable PIN screen same as the

Swifty tool for visual testing iPhone and iPad apps. Every pixel counts.

Cribble Cribble - a tool for visual testing iPhone and iPad apps. Every pixel counts. Getting Started An example app is included demonstrating Cribble

Extensions which helps to convert objc-style target/action to swifty closures

ActionClosurable Usage ActionClosurable extends UIControl, UIButton, UIRefreshControl, UIGestureRecognizer and UIBarButtonItem. It helps writing swift

Comments
  • Add `Regex#namedGroups`?

    Add `Regex#namedGroups`?

    There's currently a method Regex#group(named:) to get a single named group, but it might be nicer to just add Regex#namedGroups which would be a [String: Group] of group name and group.

    Thoughts?

    enhancement help wanted 
    opened by sindresorhus 3
  • Strongly-typed regex named groups

    Strongly-typed regex named groups

    Just an idea (untested):

    struct Result: Codable {
    	let word: String?
    	let number: Int?
    }
    
    let regex = Regex(#"\d+(?<\#(.word)>[a-z]+)(?<\#(.number)>\d+)"#, type: Result.self)
    
    let groups = regex.firstMatch(in: "123unicorn456")?.namedGroups
    
    print(groups.word)
    //=> Optional("unicorn")
    
    print(groups.number)
    //=> Optional(456)
    //             ^ Int
    

    Feedback wanted!

    opened by sindresorhus 0
  • Improve print output

    Improve print output

    The output when printing Regex, Match, and Group is a bit messy. Would be nice to add some nice representations for them. For example, Regex could have the output /foo/i, where the i comes from the .caseInsensitive option.

    enhancement help wanted 
    opened by sindresorhus 0
  • Make it Codable

    Make it Codable

    Could be useful to make Regex Codable, but not something I need right now. PR welcome if you need it.

    It needs to serialize both the expression and also the regex options.

    enhancement help wanted 
    opened by sindresorhus 0
Releases(v1.0.0)
Owner
Sindre Sorhus
Full-Time Open-Sourcerer. Wants more empathy & kindness in open source. Focuses on Swift & JavaScript. Makes macOS apps, CLI tools, npm packages. Likes unicorns
Sindre Sorhus
Swifty closures for UIKit and Foundation

Closures is an iOS Framework that adds closure handlers to many of the popular UIKit and Foundation classes. Although this framework is a substitute f

Vinnie Hesener 1.7k Dec 21, 2022
Extensions which helps to convert objc-style target/action to swifty closures

ActionClosurable Usage ActionClosurable extends UIControl, UIButton, UIRefreshControl, UIGestureRecognizer and UIBarButtonItem. It helps writing swift

takasek 121 Aug 11, 2022
Lint anything by combining the power of Swift & regular expressions.

Installation β€’ Getting Started β€’ Configuration β€’ Xcode Build Script β€’ Donation β€’ Issues β€’ Regex Cheat Sheet β€’ License AnyLint Lint any project in any

Flinesoft 116 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
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
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
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
A Cross-Platform String and Regular Expression Library written in Swift.

Guitar ?? A Cross-Platform String and Regular Expression Library written in Swift. About This library seeks to add common string manipulation function

Arthur Ariel Sabintsev 659 Dec 27, 2022
Kukai Crypto Swift is a native Swift library for creating regular or HD wallets for the Tezos blockchain

Kukai Crypto Swift Kukai Crypto Swift is a native Swift library for creating regular and HD key pairs for the Tezos blockchain. Supporting both TZ1 (E

Kukai Wallet 2 Aug 18, 2022
A charmful decade with many colors patterns, disco music, and other cultural expressions that we refer to as vintage

MontyHallProblem Welcome to the 70s! ?? That is a charmful decade with many colors patterns, disco music, and other cultural expressions that we refer

Diogo Infante 2 Dec 28, 2021