正则表达式

Swifty 正则表达式

这是 NSRegularExpression 的一个包装器,使在 Swift 中使用正则表达式更加方便和类型安全。

安装

将以下内容添加到 Package.swift

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

或者在 Xcode 中添加包。

用法

首先,导入包

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

API

请参阅 API 文档。

FAQ

为什么模式字符串要用 # 包裹?

这些是原始字符串,它们使得例如可以使用 \d 而无需转义反斜杠。

相关