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

时间:2017-03-13 09:28:34

标签: regex swift filter swift3 nsregularexpression

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

问题:我不知道如何在Swift 3中设置正则表达式。我在Swift中相当新,所以一个易于理解的解决方案将非常有用:)

目前情况如何:

 <ng2-slider 
        min="myMinVal"
        max="myMaxValue"
        value="myCurrentvalue">

 </ng2-slider>

 export class App{
     myMinVal:number=0;
     myMaxValue:number=100;
     myCurrentValue:number:30;
 }

这就是Item的样子(片段):

    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()
        }
    }

解决。我刚刚编辑了这篇文章以获得徽章:D

2 个答案:

答案 0 :(得分:2)

为了让答案变得通用和明确,我将假设Item模型是:

struct Item {
    var email = ""
}

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

对于此类功能,您应该使用NSRegularExpression

  

NSRegularExpression类用于表示和应用常规   表达式到Unicode字符串。这个类的一个例子是   编译正则表达式模式的不可变表示   各种选项标志。

根据以下功能:

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(_:)方法获取已过滤的数组:

  

返回一个数组,按顺序包含序列的元素   满足给定的谓词。

如下:

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

let emailItems = items.filter {
    isMatches(emailRegex, $0.email)
}

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

希望这会有所帮助。

答案 1 :(得分:0)

您可以使用filter功能

执行相同的操作
let matches = Storage.storage.items.filter({ $0.yourStringPropertyHere == input })