Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NSPredicate SELF MATCHES doesnt work with simple contains regex

All I need is to check using NSPredicate and evaluate pattern if my string contains .page.link phrase.

extension String {
    func isValid(for string: String) -> Bool {
        NSPredicate(format: "SELF MATCHES %@", string).evaluate(with: self)
    }
}

let pattern = ".page.link" // "\\.page\\.link"

"joyone.page.link/abcd?title=abcd".isValid(for: pattern) //false
"joyone.page.link".isValid(for: pattern) //false
"joyone.nopage.link/abcd?title=abcd".isValid(for: pattern) //false

I know there is a simpler way to do this, but it is a part of something bigger, and my pattern is just case in enum.

First two should be true.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

MATCHES considers always the whole string.

range(of:options:) can also talk Regex and is easier to use

extension String {
    func isValid(for pattern: String) -> Bool {
        range(of: pattern, options: .regularExpression) != nil
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading