确保正则表达式与Swift正则表达式匹配整个字符串

时间:2017-04-28 08:59:06

标签: regex swift

如何检查WHOLE字符串是否与正则表达式匹配?在Java中是方法String.matches(regex)

3 个答案:

答案 0 :(得分:6)

您要找的是range(of:options:range:locale:)然后您可以将范围(of:option :)的结果与整个比较字符串范围进行比较..

示例:

let phoneNumber = "(999) 555-1111"
let wholeRange = phoneNumber.startIndex..<phoneNumber.endIndex
if let match = phoneNumber.range(of: "\\(?\\d{3}\\)?\\s\\d{3}-\\d{4}", options: .regularExpression), wholeRange == match {
    print("Valid number")
}
else {
    print("Invalid number")
}
//Valid number

修改:您还可以使用NSPredicate并将字符串与其evaluate(with:)方法进行比较。

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")
}

答案 1 :(得分:3)

您需要使用锚点^(字符串锚点的开头)和$(字符串锚点的结尾)和range(of:options:range:locale:),并传递.regularExpression选项:< / p>

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仅将模式锚定在字符串的开头,您将能够省略^,但仍然需要$锚定在字符串结尾处:

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

请参阅online Swift demo

此外,将NSPredicateMATCHES一起使用是另一种选择:

  

根据ICU v3,左手表达式使用正则表达式比较等于右手表达式(有关详细信息,请参阅Regular Expressions的ICU用户指南)。

MATCHES实际上在字符串的开头和结尾都锚定了正则表达式匹配注意这可能不适用于所有Swift 3版本):< / p>

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

答案 2 :(得分:0)

Swift extract regex matches

一点点编辑

import Foundation

func matches(for regex: String, in text: String) -> Bool {
    do {
        let regex = try NSRegularExpression(pattern: regex)
        let nsString = text as NSString
        let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
        return !results.isEmpty
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return false
    }
}

上述链接的示例用法:

let string = "19320"
let matched = matches(for: "^[1-9]\\d*$", in: string)
print(matched) // will match

let string = "a19320"
let matched = matches(for: "^[1-9]\\d*$", in: string)
print(matched) // will not match