Regex capture group swift

前端 未结 1 418
谎友^
谎友^ 2021-01-13 22:37

I have a regex search method in string:

extension String {
    func searchRegex (regex: String) -> Array {
        do {
            let rege         


        
1条回答
  •  逝去的感伤
    2021-01-13 23:00

    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 = Array()
            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)
                }
            }
    

    0 讨论(0)
提交回复
热议问题