Check Regex String Matching

How to check if WHOLE string matches regular expression? Java has a methodString.matches(regex)

+4
source share
3 answers

You need to use the bindings, ^(start of string binding) and $(end of string binding) range(of:options:range:locale:), passing the parameter .regularExpression:

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 can pass an array of parameters [.regularExpression, .anchored]where .anchoredonly the string will be bound at the beginning, and you can skip ^, but still $need to bind to the end of the string:

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

Watch Swift Demo Online

, NSPredicate MATCHES :

ICU v3 ( . ICU ).

MATCHES , ( , Swift 3):

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

, , range(of:options:range:locale:), (: 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")
}
+3

Swift regex matches

with few changes

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

Example usage from the above link:

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
0
source

Source: https://habr.com/ru/post/1675885/


All Articles