skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    Of course @vadian answer is very correct and it is recommended, but here the solution is the following:

    let pattern = ".{1,}\.page\.link.{1,}"
    

    Thanks for the comment that it considers a whole string.


  2. 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
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search