【问题标题】:City Name validation Regex Swift 4城市名称验证正则表达式 Swift 4
【发布时间】:2019-01-08 19:20:42
【问题描述】:

我一直在尝试对给定的城市名称实施正则表达式验证。

我的正则表达式应该匹配城市名称,例如:

NY
San Francisco
München
København
Saint-Tropez
St. Lucia

到目前为止,我已经在网上搜索了类似的正则表达式,但我一直很难尝试在 swift 中实现它。

这是我想出的正则表达式,它似乎可以在其他语言中使用,但不能在 swift 中使用:

^[a-zA-Z\\u0080-\\u024F\\s\\/\\-\\)\(\`\.\"\']+$

作为附加信息,我想在 UITextField 委托方法中实现它:

应该改变CharactersIn

类似这样的:

override func textField(_ textField: UITextField,
                            shouldChangeCharactersIn range: NSRange,
                            replacementString string: String) -> Bool {

        return validNameRegex.matches(string)
    }

使用 NSRegularExpression 扩展:

extension NSRegularExpression {

    convenience init(_ pattern: String) {
        do {
            try self.init(pattern: pattern)
        } catch {
            preconditionFailure("Illegal regular expression: \(pattern).")
        }
    }


    func matches(_ string: String) -> Bool {
        let range = NSRange(location: 0, length: string.utf16.count)
        return firstMatch(in: string, options: [], range: range) != nil
    }
}

希望有人可以帮助我。提前谢谢,新年快乐:)

【问题讨论】:

  • 正则表达式验证究竟将用于什么?用户是否输入了城市名称并通过正则表达式从列表中对其进行验证?我觉得没有正则表达式还有其他方法可以做到这一点。
  • 是的,我会将它与从服务器返回的列表进行比较。用户在文本字段中输入后
  • 试试^[a-zA-Z\\u0080-\\u024F\\s\\/\\-\\)\\(\`\\.\\"\\']+$
  • @MarioArámbula 听起来您将针对另一个城市名称列表遍历整个列表。使用 Set 会好很多。 Set 通常比迭代列表具有更快的运行时间,因为它具有唯一值。因此,如果用户正在输入一个城市名称并且您将其放入一个 Set 中,那么您可以查看来自服务器的列表是否包含来自您的 Set 的值。这将比 Regex 更快、更高效。
  • 直接来自 Swift 文档:You use a set instead of an array when you need to test efficiently for membership and you aren’t concerned with the order of the elements in the collection, or when you need to ensure that each element appears only once in a collection.

标签: swift regex textfield city


【解决方案1】:

最后我最终使用了这个正则表达式:

^[a-zA-Z\u{0080}-\u{024F}\\s\\/\\-\\)\\(\\`\\.\\\"\\']*$

主要问题是在 unicode 中对“\”字符和 {} 进行转义

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多