正则表达式在 swift 中不起作用。给出错误"invalid regex"



我正在尝试从一个字符串中获取子字符串。为此,我正在应用regex{[^{]*},但它在我的swift代码中不起作用,并给我一个错误";无效正则表达式";。使用相同的regexhttps://regex101.com/r/B8Gwa7/1.我使用以下代码来应用正则表达式。我需要在";{"one_answers"}";。我可以在不使用正则表达式的情况下得到相同的结果吗?或者我的正则表达式或代码有什么问题吗?。

static func matches(regex: String, text: String) -> Bool {
do {
let regex = try NSRegularExpression(pattern: regex, options: [.caseInsensitive])
let nsString = text as NSString
let match = regex.firstMatch(in: text, options: [],
range: NSRange(location: .zero, length: nsString.length))
return match != nil
} catch {
print("invalid regex: (error.localizedDescription)")
return false
}
}

花括号是必须转义的特殊字符

Swift文本字符串\{[^}]*\}中的{[^}]*}

顺便说一句,不要使用NSRange的文字初始值设定项来获取字符串的长度,强烈建议使用

static func matches(regex: String, text: String) -> Bool {
do {
let regex = try NSRegularExpression(pattern: regex, options: .caseInsensitive)
let match = regex.firstMatch(in: text, options: [],
range: NSRange(text.startIndex..., in: text)
return match != nil
} catch {
print("invalid regex: (error.localizedDescription)")
return false
}
}

相关内容

最新更新