Make sure regex matches the entire string with Swift regex

后端 未结 3 1002
萌比男神i
萌比男神i 2020-12-04 01:39

How to check whether a WHOLE string can be matches to regex? In Java is method String.matches(regex)

3条回答
  •  渐次进展
    2020-12-04 02:29

    What you are looking for is range(of:options:range:locale:) then you can then compare the result of range(of:option:) with whole range of comparing string..

    Example:

    let phoneNumber = "(999) 555-1111"
    let wholeRange = phoneNumber.startIndex..

    Edit: You can also use NSPredicate and compare your string with evaluate(with:) method of its.

    let pattern = "^\\(?\\d{3}\\)?\\s\\d{3}-\\d{4}$"
    let predicate = NSPredicate(format: "self MATCHES [c] %@", pattern)
    if predicate.evaluate(with: "(888) 555-1111") {
        print("Valid")
    }
    else {
        print("Invalid")
    }
    

提交回复
热议问题