sindresorhus/regex
> Swifty [regular expressions](https://en.wikipedia.org/wiki/Regular_expression)
Install
Add the following to Package.swift:
.package(url: "https://github.com/sindresorhus/Regex", from: "1.1.0")Usage
First, import the package:
import RegexExamples
Check if it matches:
Regex(#"\d+"#).isMatched(by: "123")
//=> trueGet 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"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")
//=> trueAPI
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.
Package Metadata
Repository: sindresorhus/regex
Default branch: main
README: readme.md