将 JavaScript 正则表达式转换为 Swift 正则表达式

Cyc*_*oke 1 regex swift

我正在学习 Swift,我正在尝试将一小段 JavaScript 代码转换为 Swift。JavaScript 代码使用 Regex 拆分字符串,如下所示:

var text = "blah.clah##something_else";
var parts = text.match(/(^.*?)\#\#(.+$)/);
Run Code Online (Sandbox Code Playgroud)

执行后,该parts数组将包含以下内容:

["blah.clah##something_else", "blah.clah", "something_else"]
Run Code Online (Sandbox Code Playgroud)

我想在 Swift 中复制相同的行为。下面是我编写的使用正则表达式将字符串拆分为字符串数组的 Swift 代码:

func matchesForRegexInText(regex: String!, text: String!) -> [String] {
do {
    let regex = try NSRegularExpression(pattern: regex, options: NSRegularExpressionOptions.CaseInsensitive)
    let nsString = text as NSString
    let results = regex.matchesInString(text,
        options: NSMatchingOptions.ReportCompletion , range: NSMakeRange(0, nsString.length))
        as [NSTextCheckingResult]
    return results.map({
        nsString.substringWithRange($0.range)
    })
} catch {
    print("exception")
    return [""]
}
Run Code Online (Sandbox Code Playgroud)

}

当我使用以下命令调用上述函数时:

matchesForRegexInText("(^.*?)\\#\\#(.+$)", text: "blah.clah##something_else")
Run Code Online (Sandbox Code Playgroud)

我得到以下信息:

["blah.clah##something_else"]
Run Code Online (Sandbox Code Playgroud)

我尝试了许多不同的 Regex,但没有成功。Regex (^.*?)\#\#(.+$) 是否正确,或者matchesForRegexInText() 函数有问题?我很欣赏任何见解。

我使用的是 Swift 2 和 Xcode 7.0 测试版 (7A120f)

Mar*_*n R 5

作为一个评论已经提到的,你的模式匹配的整个 字符串,因此regex.matchesInString()返回一个 NSTextCheckingResultrange描述整个字符串。您正在寻找的是与 您的模式中的捕获组匹配的子字符串。这些可用rangeAtIndex(i)i >= 1

func matchesForRegexInText(regex: String!, text: String!) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        guard let result = regex.firstMatchInString(text, options: [], range: NSMakeRange(0, nsString.length)) else {
            return [] // pattern does not match the string
        }
        return (1 ..< result.numberOfRanges).map {
            nsString.substringWithRange(result.rangeAtIndex($0))
        }
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}
Run Code Online (Sandbox Code Playgroud)

例子:

let matches = matchesForRegexInText("(^.*?)##(.+$)", text: "blah.clah##something_else")
print(matches)
// [blah.clah, something_else]
Run Code Online (Sandbox Code Playgroud)

  • 太棒了。感谢您的解释和更新的代码。 (2认同)