【发布时间】:2021-06-10 05:57:20
【问题描述】:
我正在尝试从一个字符串中获取子字符串。为此,我正在应用正则表达式 {[^{]*} 但它在我的快速代码中不起作用并给我一个错误“无效的正则表达式”。相同的正则表达式正在使用https://regex101.com/r/B8Gwa7/1。我正在使用以下代码来应用正则表达式。我需要获取“{”和“}”之间的子字符串。我可以在不使用正则表达式的情况下得到相同的结果吗?或者我的正则表达式或代码有什么问题吗?。
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
}
}
【问题讨论】:
-
首先,你想要这样的正则表达式
{[^}]*}其次,尝试转义字符,例如{和} -
@MichałTurczyn 尝试使用
{[^}]*},但仍然遇到同样的错误。 -
逃脱它。例如。
#"\{.*?\}"#或#"\{[^}]*\}"#.
标签: ios swift objective-c regex swift5