代码之家  ›  专栏  ›  技术社区  ›  Heuristic

ios字符串范围(of:options:range:locale:)对有效的regex有效

  •  0
  • Heuristic  · 技术社区  · 6 年前

    我通过以下方法检查字符串是否与regex匹配:

    string.range(of: self.regularExpression, options: .regularExpression, range: nil, locale: nil) != nil
    

    正则表达式:

    ^[!-@[-~][ -@[-~]{0,254}[!-@[-~]$
    

    我已经通过一些在线验证工具验证了regex,但在ios中,它不适用于同一个字符串,例如:“company”。有什么不对的,比如正则表达式中的字符需要转义吗?

    谢谢!

    1 回复  |  直到 6 年前
        1
  •  0
  •   rmaddy    6 年前

    你需要逃离 [ 里面 [ ] .

    ^[!-@\\[-~][ -@\\[-~]{0,254}[!-@\\[-~]$
    

    你也可以用:

    ^[!-~][ -~]{0,254}[!-~]$
    

    如果你在 lowercased() 字符串。