问题描述
我想从匹配正则表达式模式的字符串中提取子字符串。
I want to extract substrings from a string that match a regex pattern.
所以我正在寻找类似的东西:
So I'm looking for something like this:
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
???
}
所以这就是我所拥有的:
So this is what I have:
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
。
The problem is, that matchesInString
delivers me an array of NSTextCheckingResult
, where NSTextCheckingResult.range
is of type NSRange
.
NSRange
与范围< String.Index>
,所以它阻止我使用 text.substringWithRange(...)
NSRange
is incompatible with Range<String.Index>
, so it prevents me of using text.substringWithRange(...)
任何想法如何实现这个没有太多代码行的swift中的简单事情?
Any idea how to achieve this simple thing in swift without too many lines of code?
推荐答案
即使 matchesInString()
方法将 String
作为第一个参数,
它在内部使用 NSString
,并且range参数必须使用 NSString
长度而不是Swift字符串长度给出
。否则,
将失败扩展字形集群,例如flags。
Even if the matchesInString()
method takes a String
as the first argument,it works internally with NSString
, and the range parameter must be given using the NSString
length and not as the Swift string length. Otherwise it willfail for "extended grapheme clusters" such as "flags".
从 Swift 4 (Xcode 9)开始,Swift标准的
库提供了在 Range< String.Index>
和 NSRange $ c $之间转换的函数c>。
As of Swift 4 (Xcode 9), the Swift standardlibrary provides functions to convert between Range<String.Index>
and 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 []
}
}
示例:
这篇关于Swift提取正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!