Make sure regex matches the entire string with Swift regex

后端 未结 3 1012
萌比男神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:41

    You need to use anchors, ^ (start of string anchor) and $ (end of string anchor), with range(of:options:range:locale:), passing the .regularExpression option:

    import Foundation
    
    let phoneNumber = "123-456-789"
    let result = phoneNumber.range(of: "^\\d{3}-\\d{3}-\\d{3}$", options: .regularExpression) != nil
    print(result)
    

    Or, you may pass an array of options, [.regularExpression, .anchored], where .anchored will anchor the pattern at the start of the string only, and you will be able to omit ^, but still, $ will be required to anchor at the string end:

    let result = phoneNumber.range(of: "\\d{3}-\\d{3}-\\d{3}$", options: [.regularExpression, .anchored]) != nil
    

    See the online Swift demo

    Also, using NSPredicate with MATCHES is an alternative here:

    The left hand expression equals the right hand expression using a regex-style comparison according to ICU v3 (for more details see the ICU User Guide for Regular Expressions).

    MATCHES actually anchors the regex match both at the start and end of the string (note this might not work in all Swift 3 builds):

    let pattern = "\\d{3}-\\d{3}-\\d{3}"
    let predicate = NSPredicate(format: "self MATCHES [c] %@", pattern)
    let result = predicate.evaluate(with: "123-456-789") 
    

提交回复
热议问题