如何检查一个 WHOLE 字符串是否可以匹配正则表达式?在 Java 中是方法 String.matches(regex)
How to check whether a WHOLE string can be matches to regex? In Java is method String.matches(regex)
推荐答案你需要使用锚点,^(字符串锚点的开始)和$(字符串的结束)锚点),带有 range(of:options:range:locale:),传递.regularExpression 选项:
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)或者,您可以传递一组选项,[.regularExpression, .anchored],其中 .anchored 只会将模式锚定在字符串的开头,您可以省略 ^,但仍然需要 $ 锚定在字符串末尾:
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查看在线 Swift 演示
此外,使用 NSPredicate 和 MATCHES 是这里的替代:
Also, using NSPredicate with MATCHES is an alternative here:
左手表达式等于右手表达式,根据 ICU v3 使用正则表达式样式比较(有关更多详细信息,请参阅 正则表达式).
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 实际上在字符串的开头和结尾都锚定了正则表达式匹配(注意这可能不适用于所有 Swift 3 版本):
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")更多推荐
确保正则表达式与 Swift 正则表达式匹配整个字符串
发布评论