如何在NSRegularExpression中找到匹配的组

时间:2015-04-01 16:29:19

标签: regex swift nsregularexpression

我有一个带有多个捕获组的正则表达式语句,它们由|分隔运营商。如何找出匹配的捕获组?我能想到的唯一方法 - 就这个例子而言 - 是在匹配某些东西的情况下计算字符数。

var string = "1234567897"
var pattern = "(^\\d{9}$)|(^\\d{10}$)|(^\\d{13}$)|(^[a-zA-Z]{2}\\d{9}[a-zA-Z]{2}$)"

var myRegex = NSRegularExpression(pattern: pattern, options: nil, error: nil)!

if let myMatch = myRegex.firstMatchInString(string, options: nil,
    range: NSRange(location: 0, length: string.utf16Count)) {
        println((string as NSString).substringWithRange(myMatch.rangeAtIndex(0)))

}

1 个答案:

答案 0 :(得分:2)

我编写了一个适用于我的例子的代码。我相信它可以写得更好,但它现在有效。

Swift 2.3

var string = "123456789"
var pattern = "(^\\d{9}$)|(^\\d{10}$)|(^\\d{13}$)|(^[a-zA-Z]{2}\\d{9}[wW]{2}$)"

var myRegex = try! NSRegularExpression(pattern: pattern, options: [])

if let myMatch = myRegex.firstMatchInString(string, options: NSMatchingOptions.init(rawValue: 0), range: NSRange(location: 0, length: string.utf16.count)) {
    var matchedGroup = 0

    for var i in 1..<myMatch.numberOfRanges {
        if myMatch.rangeAtIndex(i).length != 0 {
            matchedGroup = i
            break
        }

    }
    print(matchedGroup)
    print((string as NSString).substringWithRange(myMatch.rangeAtIndex(0))) //whatever the range you want to print

}

Swift 3

var string = "123456789"
var pattern = "(^\\d{9}$)|(^\\d{10}$)|(^\\d{13}$)|(^[a-zA-Z]{2}\\d{9}[wW]{2}$)"

var myRegex = try! NSRegularExpression(pattern: pattern, options: [])

if let myMatch = myRegex.firstMatch(in: string, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSRange(location: 0, length: string.utf16.count)) {
    var matchedGroup = 0

    for var i in 1..<myMatch.numberOfRanges {
        if myMatch.rangeAt(i).length != 0 {
            matchedGroup = i
            break
        }

    }
    print(matchedGroup)
    print((string as NSString).substring(with: myMatch.rangeAt(0))) //whatever the range you want to print

}