Swiftpack.co - sindresorhus/Regex as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by sindresorhus.
sindresorhus/Regex v1.0.0
🔤 Swifty regular expressions
⭐️ 327
🕓 2 years ago
iOS macOS watchOS tvOS
.package(url: "https://github.com/sindresorhus/Regex.git", from: "v1.0.0")

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:

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

Get first match:

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

Get all matches:

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

Replacing first match:

"123🦄456".replacingFirstMatch(of: #"\d+"#, with: "")
//=> "🦄456"

Replacing all matches:

"123🦄456".replacingAllMatches(of: #"\d+"#, with: "")
//=> "🦄"

Named capture groups:

let regex = Regex(#"\d+(?<word>[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:

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

GitHub

link
Stars: 327
Last commit: 1 year ago
Advertisement: IndiePitcher.com - Cold Email Software for Startups

Release Notes

2 years ago
  • No changes. This just marks the package as stable.

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics