swift - 在 Swift 中使用特殊字符转义正则表达式

标签 swift regex

我有一个相对复杂的正则表达式,需要在 Swift 中运行。原来是:

“typedef\W+struct\W+{([^}]*)}\W+(\w+);”

您可以看到在 JS 中工作的模式 here .

为了让它在 Swift 中编译,我将反斜杠转义为:

“typedef\\W+struct\\W+{([^}]*)}\\W+(\\w+);”

在运行时,表达式无法编译并出现 2048 错误。我也尝试转义其他字符并尝试 escapedPatternForString 但没有成功。是否有将 JS 正则表达式转换为 Swift 的脚本?谢谢!

最佳答案

您需要转义字符类外部{}:

let rx = "typedef\\W+struct\\W+\\{([^}]*)\\}\\W+(\\w+);"

快速演示:

let rx = "typedef\\W+struct\\W+\\{([^}]*)\\}\\W+(\\w+);"
let str = "typedef: struct { something } text;"
print(str.range(of: rx, options: .regularExpression) != nil) 
// => true

{} 在字符类中时,它们可能保持未转义(如 [^}])。

使用 this code (由 Confused Vorlon 回答),您可能会得到所有捕获组的第一个匹配项:

extension NSTextCheckingResult {
    func groups(testedString:String) -> [String] {
        var groups = [String]()
        for i in  0 ..< self.numberOfRanges
        {
            let group = String(testedString[Range(self.range(at: i), in: testedString)!])
            groups.append(group)
        }
        return groups
    }
}

let str = "typedef: struct { something } text;"
let rx = "typedef\\W+struct\\W+\\{([^}]*)\\}\\W+(\\w+);"
let MyRegex = try! NSRegularExpression(pattern: rx)
if let match = MyRegex.firstMatch(in: str, range: NSMakeRange(0, str.count)) {
     let groups = match.groups(testedString: str)
     print(groups)
}
// => ["typedef: struct { something } text;", " something ", "text"]

关于swift - 在 Swift 中使用特殊字符转义正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54597972/

相关文章:

PHP Regex去除多余的标点符号

regex - 旧版本支持 Perl 棘手的正则表达式转换

ios - 从 firebase 检索我的帖子并将其显示在我的 collectionView 单元格上? ios

ios - 根据tableView的高度设置动态的View高度

ios - 类型 'MyWeather'不符合协议(protocol) 'Encodable'错误

Javascript Regexp - 匹配特定短语后的字符

ruby - 使用正则表达式将 ruby 字符串分块

ios - 如何在 swift 中允许电子邮件字符串中存在空格?

swift - RealityKit – 以编程方式设置 Reality Composer 实体的文本

swift - 什么是 _ : in Swift telling me?