【问题标题】:Regex not working in swift. Giving an error "invalid regex"正则表达式不能快速工作。给出错误“无效的正则表达式”
【发布时间】: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


【解决方案1】:

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

\{[^}]*\},在 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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 2021-02-01
    • 1970-01-01
    相关资源
    最近更新 更多