Swift:通过正则表达式查找对象 属性

Swift: Finding an Object Property via regex

目标:以下函数应遍历对象数组并检查所有对象的特定 属性。此 属性 是一个字符串,应通过正则表达式与用户输入匹配。如果匹配,则应将对象添加到数组中,该数组将进一步传递给另一个函数。

问题:我不知道如何在 Swift 3 中设置正则表达式。我对 Swift 完全陌生,所以一个易于理解的解决方案将非常有帮助:)

目前的样子:

    func searchItems() -> [Item] {
        var matches: [Item] = []
        if let input = readLine() {
            for item in Storage.storage.items {    //items is a list of objects
                if let query = //regex with query and item.name goes here {
                    matches.append(item)
                }
            }
            return matches
        } else {
            print("Please type in what you're looking for.")
            return searchItems()
        }
    }

这是项目的样子(片段):

    class Item: CustomStringConvertible {

        var name: String = ""
        var amount: Int = 0
        var price: Float = 0.00
        var tags: [String] = []
        var description: String {
            if self.amount > 0 {
                return "\(self.name) (\(self.amount) pcs. in storage) - \(price) €"
            } else {
                return "\(self.name) (SOLD OUT!!!) - \(price) €"
            }
        }

        init(name: String, price: Float, amount: Int = 0) {
            self.name = name
            self.price = price
           self.amount = amount
        }
    }

    extension Item: Equatable {

        static func ==(lhs: Item, rhs: Item) -> Bool {
            return lhs.name == rhs.name
        }

    }

已解决。我刚刚编辑了这个 post 以获得徽章 :D

你可以用 filter 函数做同样的事情

let matches = Storage.storage.items.filter({ [=10=].yourStringPropertyHere == input })

为了让答案通用和清晰,我假设 Item 模型是:

struct Item {
    var email = ""
}

考虑输出应该是一个过滤项目数组,其中包含只有有效电子邮件的项目。

对于这样的功能,您应该使用 NSRegularExpression:

The NSRegularExpression class is used to represent and apply regular expressions to Unicode strings. An instance of this class is an immutable representation of a compiled regular expression pattern and various option flags.

根据以下函数:

func isMatches(_ regex: String, _ string: String) -> Bool {
    do {
        let regex = try NSRegularExpression(pattern: regex)

        let matches = regex.matches(in: string, range: NSRange(location: 0, length: string.characters.count))
        return matches.count != 0
    } catch {
        print("Something went wrong! Error: \(error.localizedDescription)")
    }

    return false
}

您可以决定给定的 string 是否与给定的 regex 匹配。

回到示例,假设您有以下 Item 模型数组:

let items = [Item(email: "invalid email"),
             Item(email: "email@email.com"),
             Item(email: "Hello!"),
             Item(email: "example@example.net")]

您可以使用filter(_:)方法获取过滤后的数组:

Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.

如下:

let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"

let emailItems = items.filter {
    isMatches(emailRegex, [=13=].email)
}

print(emailItems) // [Item(email: "email@email.com"), Item(email: "example@example.net")]

希望对您有所帮助。