问题描述
我在字符串中有一个正则表达式搜索方法:
I have a regex search method in string:
extension String {
func searchRegex (regex: String) -> Array<String> {
do {
let regex = try NSRegularExpression(pattern: regex, options: NSRegularExpressionOptions(rawValue: 0))
let nsstr = self as NSString
let all = NSRange(location: 0, length: nsstr.length)
var matches : Array<String> = Array<String>()
regex.enumerateMatchesInString(self, options: NSMatchingOptions(rawValue: 0), range: all) {
(result : NSTextCheckingResult?, _, _) in
let theResult = nsstr.substringWithRange(result!.range)
matches.append(theResult)
}
return matches
} catch {
return Array<String>()
}
}
}
它运作良好。但如果我有正则表达式 product_title:\ ['(。*)'
它会返回 product_title:[\'s标题bla bla \'
但我只需要零件(。*)
。
It works good. But if i have a regular expression product_title:\['(.*)'
it returns me product_title:[\'Some title bla bla\'
but i only need the part (.*)
.
I我是swift的新手,但是在python中这个问题通过使用 groups()
函数解决了。如何在swift中使用捕获组。请举个例子。
I'm new in swift, but in python this problem solved by using groups()
function. How to use capture group in swift. Please give me example.
推荐答案
NSTextCheckingResult
有 numberOfRanges
属性和 rangeAtIndex()
方法,可让您获取各个捕获组的范围。因此,如果您想要第一个捕获组而不是整个匹配的字符串,您可以将代码修改为:
NSTextCheckingResult
has a numberOfRanges
property and a rangeAtIndex()
method that lets you grab the range for individual capture groups. So if you wanted the first capture group instead of the whole matched string, you would modify your code to:
var matches : Array<String> = Array<String>()
regex.enumerateMatchesInString(self, options: NSMatchingOptions(rawValue: 0), range: all) {(result : NSTextCheckingResult?, _, _) in
let capturedRange = result!.rangeAtIndex(1)
if !NSEqualRanges(capturedRange, NSMakeRange(NSNotFound, 0)) {
let theResult = nsstr.substringWithRange(result!.rangeAtIndex(1))
matches.append(theResult)
}
}
这篇关于正则表达式捕获组迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!