Swifty 正则表达式
这是 NSRegularExpression
的一个包装器,使在 Swift 中使用正则表达式更加方便和类型安全。
将以下内容添加到 Package.swift
.package(url: "https://github.com/sindresorhus/Regex", from: "0.1.0")
首先,导入包
import Regex
检查是否匹配
Regex(#"\d+"#).isMatched(by: "123")
//=> true
获取首次匹配
Regex(#"\d+"#).firstMatch(in: "123-456")?.value
//=> "123"
获取所有匹配项
Regex(#"\d+"#).allMatches(in: "123-456").map(\.value)
//=> ["123", "456"]
替换首次匹配项
"123🦄456".replacingFirstMatch(of: #"\d+"#, with: "")
//=> "🦄456"
替换所有匹配项
"123🦄456".replacingAllMatches(of: #"\d+"#, with: "")
//=> "🦄"
命名捕获组
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
}
多行和注释
let regex = Regex(
#"""
^
[a-z]+ # Match the word
\d+ # Match the number
$
"""#,
options: .allowCommentsAndWhitespace
)
regex.isMatched(by: "foo123")
//=> true
这些是原始字符串,它们使得例如可以使用 \d
而无需转义反斜杠。