我有一个相对复杂的正则表达式,需要在 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/