[英]Swift extract regex matches
我想从匹配正则表达式模式的字符串中提取子字符串。
所以我正在寻找这样的东西:
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
???
}
所以这就是我所拥有的:
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
var regex = NSRegularExpression(pattern: regex,
options: nil, error: nil)
var results = regex.matchesInString(text,
options: nil, range: NSMakeRange(0, countElements(text)))
as Array<NSTextCheckingResult>
/// ???
return ...
}
问题是, matchesInString
为我提供了一个NSTextCheckingResult
数组,其中NSTextCheckingResult.range
是NSRange
类型。
NSRange
与Range<String.Index>
不兼容,所以它阻止我使用text.substringWithRange(...)
知道如何在没有太多代码行的情况下在 swift 中实现这个简单的事情吗?
即使matchesInString()
方法将String
作为第一个参数,它在内部也可以使用NSString
,并且必须使用NSString
长度而不是 Swift 字符串长度来给出范围参数。 否则对于“扩展字形簇”(例如“标志”)将失败。
从Swift 4 (Xcode 9) 开始,Swift 标准库提供了在Range<String.Index>
和NSRange
之间转换的函数。
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
String(text[Range($0.range, in: text)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
例子:
let string = "🇩🇪€4€9"
let matched = matches(for: "[0-9]", in: string)
print(matched)
// ["4", "9"]
注意:强制展开Range($0.range, in: text)!
是安全的,因为NSRange
引用给定字符串text
的子字符串。 但是,如果您想避免它,请使用
return results.flatMap {
Range($0.range, in: text).map { String(text[$0]) }
}
反而。
(Swift 3 及更早版本的旧答案:)
因此,您应该将给定的 Swift 字符串转换为NSString
,然后提取范围。 结果将自动转换为 Swift 字符串数组。
(Swift 1.2 的代码可以在编辑历史中找到。)
斯威夫特 2(Xcode 7.3.1):
func matchesForRegexInText(regex: String, text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text,
options: [], range: NSMakeRange(0, nsString.length))
return results.map { nsString.substringWithRange($0.range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
例子:
let string = "🇩🇪€4€9"
let matches = matchesForRegexInText("[0-9]", text: string)
print(matches)
// ["4", "9"]
斯威夫特 3 (Xcode 8)
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = text as NSString
let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range)}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
例子:
let string = "🇩🇪€4€9"
let matched = matches(for: "[0-9]", in: string)
print(matched)
// ["4", "9"]
我的答案建立在给定答案之上,但通过添加额外的支持使正则表达式匹配更加健壮:
do/catch
并使用guard
结构matchingStrings
作为对String
的扩展斯威夫特 4.2
//: Playground - noun: a place where people can play
import Foundation
extension String {
func matchingStrings(regex: String) -> [[String]] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map {
result.range(at: $0).location != NSNotFound
? nsString.substring(with: result.range(at: $0))
: ""
}
}
}
}
"prefix12 aaa3 prefix45".matchingStrings(regex: "fix([0-9])([0-9])")
// Prints: [["fix12", "1", "2"], ["fix45", "4", "5"]]
"prefix12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// Prints: [["prefix12", "12"]]
"12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// Prints: [["12", "12"]], other answers return an empty array here
// Safely accessing the capture of the first match (if any):
let number = "prefix12suffix".matchingStrings(regex: "fix([0-9]+)su").first?[1]
// Prints: Optional("12")
斯威夫特 3
//: Playground - noun: a place where people can play
import Foundation
extension String {
func matchingStrings(regex: String) -> [[String]] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map {
result.rangeAt($0).location != NSNotFound
? nsString.substring(with: result.rangeAt($0))
: ""
}
}
}
}
"prefix12 aaa3 prefix45".matchingStrings(regex: "fix([0-9])([0-9])")
// Prints: [["fix12", "1", "2"], ["fix45", "4", "5"]]
"prefix12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// Prints: [["prefix12", "12"]]
"12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// Prints: [["12", "12"]], other answers return an empty array here
// Safely accessing the capture of the first match (if any):
let number = "prefix12suffix".matchingStrings(regex: "fix([0-9]+)su").first?[1]
// Prints: Optional("12")
斯威夫特 2
extension String {
func matchingStrings(regex: String) -> [[String]] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString
let results = regex.matchesInString(self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map {
result.rangeAtIndex($0).location != NSNotFound
? nsString.substringWithRange(result.rangeAtIndex($0))
: ""
}
}
}
}
extension String {
func match(_ regex: String) -> [[String]] {
let nsString = self as NSString
return (try? NSRegularExpression(pattern: regex, options: []))?.matches(in: self, options: [], range: NSMakeRange(0, nsString.length)).map { match in
(0..<match.numberOfRanges).map { match.range(at: $0).location == NSNotFound ? "" : nsString.substring(with: match.range(at: $0)) }
} ?? []
}
}
返回一个二维字符串数组:
"prefix12suffix fix1su".match("fix([0-9]+)su")
返回...
[["fix12su", "12"], ["fix1su", "1"]]
// First element of sub-array is the match
// All subsequent elements are the capture groups
如果您想从字符串中提取子字符串,不仅仅是位置,(而是实际的字符串,包括表情符号)。 那么,以下可能是一个更简单的解决方案。
extension String {
func regex (pattern: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: 0))
let nsstr = self as NSString
let all = NSRange(location: 0, length: nsstr.length)
var matches : [String] = [String]()
regex.enumerateMatchesInString(self, options: NSMatchingOptions(rawValue: 0), range: all) {
(result : NSTextCheckingResult?, _, _) in
if let r = result {
let result = nsstr.substringWithRange(r.range) as String
matches.append(result)
}
}
return matches
} catch {
return [String]()
}
}
}
示例用法:
"someText 👿🏅👿⚽️ pig".regex("👿⚽️")
将返回以下内容:
["👿⚽️"]
注意使用 "\w+" 可能会产生意外的 ""
"someText 👿🏅👿⚽️ pig".regex("\\w+")
将返回此字符串数组
["someText", "️", "pig"]
我发现不幸的是,接受的答案的解决方案无法在 Swift 3 for Linux 上编译。 那么,这是一个修改后的版本:
import Foundation
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try RegularExpression(pattern: regex, options: [])
let nsString = NSString(string: text)
let results = regex.matches(in: text, options: [], range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range) }
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
主要区别在于:
Linux 上的 Swift 似乎需要在 Foundation 对象上删除NS
前缀,而没有 Swift 原生的等效对象。 (参见Swift 进化提案 #86 。)
Linux 上的 Swift 还需要为正则RegularExpression
初始化和matches
方法指定options
参数。
出于某种原因,将String
强制转换为NSString
在 Linux 上的 Swift 中不起作用,但使用String
初始化一个新的NSString
作为源代码确实有效。
此版本也适用于 macOS / Xcode 上的 Swift 3,唯一的例外是您必须使用名称NSRegularExpression
而不是RegularExpression
。
没有 NSString 的 Swift 4。
extension String {
func matches(regex: String) -> [String] {
guard let regex = try? NSRegularExpression(pattern: regex, options: [.caseInsensitive]) else { return [] }
let matches = regex.matches(in: self, options: [], range: NSMakeRange(0, self.count))
return matches.map { match in
return String(self[Range(match.range, in: self)!])
}
}
}
@p4bloch 如果要从一系列捕获括号中捕获结果,则需要使用 NSTextCheckingResult 的NSTextCheckingResult
rangeAtIndex(index)
方法,而不是range
。 这是上面的 @MartinR 用于 Swift2 的方法,适用于捕获括号。 在返回的数组中,第一个结果[0]
是整个捕获,然后各个捕获组从[1]
开始。 我注释掉了map
操作(这样更容易看到我改变了什么)并用嵌套循环替换它。
func matches(for regex: String!, in text: String!) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text, options: [], range: NSMakeRange(0, nsString.length))
var match = [String]()
for result in results {
for i in 0..<result.numberOfRanges {
match.append(nsString.substringWithRange( result.rangeAtIndex(i) ))
}
}
return match
//return results.map { nsString.substringWithRange( $0.range )} //rangeAtIndex(0)
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
一个示例用例可能是,假设您要拆分一串title year
例如“Finding Dory 2016”,您可以这样做:
print ( matches(for: "^(.+)\\s(\\d{4})" , in: "Finding Dory 2016"))
// ["Finding Dory 2016", "Finding Dory", "2016"]
上面的大多数解决方案只给出完全匹配,结果忽略了捕获组,例如:^\d+\s+(\d+)
要按预期获得捕获组匹配,您需要类似 (Swift4) 的内容:
public extension String {
public func capturedGroups(withRegex pattern: String) -> [String] {
var results = [String]()
var regex: NSRegularExpression
do {
regex = try NSRegularExpression(pattern: pattern, options: [])
} catch {
return results
}
let matches = regex.matches(in: self, options: [], range: NSRange(location:0, length: self.count))
guard let match = matches.first else { return results }
let lastRangeIndex = match.numberOfRanges - 1
guard lastRangeIndex >= 1 else { return results }
for i in 1...lastRangeIndex {
let capturedGroupIndex = match.range(at: i)
let matchedString = (self as NSString).substring(with: capturedGroupIndex)
results.append(matchedString)
}
return results
}
}
我就是这样做的,我希望它能带来一个新的视角,它是如何在 Swift 上工作的。
在下面的这个例子中,我将得到[]
之间的任何字符串
var sample = "this is an [hello] amazing [world]"
var regex = NSRegularExpression(pattern: "\\[.+?\\]"
, options: NSRegularExpressionOptions.CaseInsensitive
, error: nil)
var matches = regex?.matchesInString(sample, options: nil
, range: NSMakeRange(0, countElements(sample))) as Array<NSTextCheckingResult>
for match in matches {
let r = (sample as NSString).substringWithRange(match.range)//cast to NSString is required to match range format.
println("found= \(r)")
}
这是一个非常简单的解决方案,它返回一个包含匹配项的字符串数组
斯威夫特 3。
internal func stringsMatching(regularExpressionPattern: String, options: NSRegularExpression.Options = []) -> [String] {
guard let regex = try? NSRegularExpression(pattern: regularExpressionPattern, options: options) else {
return []
}
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map {
nsString.substring(with: $0.range)
}
}
基本电话号码匹配
let phoneNumbers = ["+79990001101", "+7 (800) 000-11-02", "+34 507 574 147 ", "+1-202-555-0118"]
let match: (String) -> String = {
$0.replacingOccurrences(of: #"[^\d+]"#, with: "", options: .regularExpression)
}
print(phoneNumbers.map(match))
// ["+79990001101", "+78000001102", "+34507574147", "+12025550118"]
非常感谢Lars Blumberg ,他回答了用Swift 4捕获组和完整匹配,这对我有很大帮助。 当他们的正则表达式无效时,我还为那些确实想要 error.localizedDescription 响应的人添加了它:
extension String {
func matchingStrings(regex: String) -> [[String]] {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map {
result.range(at: $0).location != NSNotFound
? nsString.substring(with: result.range(at: $0))
: ""
}
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
}
对我来说,将localizedDescription 作为错误有助于理解转义出了什么问题,因为它显示了最终的正则表达式 swift 尝试实现哪个。
将@Mike Chirico 更新为Swift 5
extension String{
func regex(pattern: String) -> [String]?{
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options(rawValue: 0))
let all = NSRange(location: 0, length: count)
var matches = [String]()
regex.enumerateMatches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: all) {
(result : NSTextCheckingResult?, _, _) in
if let r = result {
let nsstr = self as NSString
let result = nsstr.substring(with: r.range) as String
matches.append(result)
}
}
return matches
} catch {
return nil
}
}
}
Regex
, RegexBuilder
👷♀️ Xcode 以前通过Find and Search
选项卡支持 Regex。 许多人发现 Apple 的NSRegularExpression
的 Swift API 冗长且笨拙,因此 Apple 在今年发布了Regex literal
支持和RegexBuilder
。
该 API 已被简化,以便在 iOS 16 / macOS 13 中整理复杂的基于String
范围的解析逻辑并提高性能。
func parseLine(_ line: Substring) throws -> MailmapEntry {
let regex = /\h*([^<#]+?)??\h*<([^>#]+)>\h*(?:#|\Z)/
guard let match = line.prefixMatch(of: regex) else {
throw MailmapError.badLine
}
return MailmapEntry(name: match.1, email: match.2)
}
目前,我们可以使用prefixMatch
或wholeMatch
进行匹配以找到单个匹配项,但未来 API 可能会针对多个匹配项进行改进。
RegexBuilder 是 Apple 发布的新 API,旨在使 RegEx 代码更容易在 Swift 中编写。 我们可以将正则表达式文字/\h*([^<#]+?)??\h*<([^>#]+)>\h*(?:#|\Z)/
从上面翻译成如果我们想要更多的可读性,请使用 RegexBuilder 更多的声明形式。
请注意,如果我们想平衡可读性和简洁性,我们可以在 RegexBuilder 中使用原始字符串,也可以在构建器中交错 Regex Literals。
import RegexBuilder
let regex = Regex {
ZeroOrMore(.horizontalWhitespace)
Optionally {
Capture(OneOrMore(.noneOf("<#")))
}
.repetitionBehavior(.reluctant)
ZeroOrMore(.horizontalWhitespace)
"<"
Capture(OneOrMore(.noneOf(">#")))
">"
ZeroOrMore(.horizontalWhitespace)
/#|\Z/
}
RegEx 文字/£|\Z/
等价于:
ChoiceOf {
"#"
Anchor.endOfSubjectBeforeNewline
}
RegexComponent
RegexBuilder
语法在可组合性方面也类似于 SwiftUI,因为我们可以在其他RegexComponent
中重用RegexComponent
:
struct MailmapLine: RegexComponent {
@RegexComponentBuilder
var regex: Regex<(Substring, Substring?, Substring)> {
ZeroOrMore(.horizontalWhitespace)
Optionally {
Capture(OneOrMore(.noneOf("<#")))
}
.repetitionBehavior(.reluctant)
ZeroOrMore(.horizontalWhitespace)
"<"
Capture(OneOrMore(.noneOf(">#")))
">"
ZeroOrMore(.horizontalWhitespace)
ChoiceOf {
"#"
Anchor.endOfSubjectBeforeNewline
}
}
}
您可以在字符串上使用matching(regex:)
,例如:
let array = try "Your String To Search".matching(regex: ".")
使用这个简单的扩展:
public extension String {
func matching(regex: String) throws -> [String] {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: self, range: NSRange(startIndex..., in: self))
return results.map { String(self[Range($0.range, in: self)!]) }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.