Search code examples
iosswiftregexstringcharacter

Regex for Minimum and Maximum Numbers in String in Swift


What is the regex for knowing if the number of characters in a string has minimum and maximum number of characters and should be numbers not letters or symbols? It doesn't have to match the same numbers, just the number of characters in the string of numbers.

I'm using this regex pattern "\\d{3,16}$" but it is not working. It only works if the number of characters is less than 3 but not when the number of characters is more than 16.

This is my code:

static func isValidMobileNumber(str: String) -> Bool {
    let range = NSRange(location: 0, length: str.utf16.count)
    let regex = try! NSRegularExpression(pattern: "\\d{3,16}$")
    return regex.firstMatch(in: str, options: [], range: range) != nil
}

I'm checking it like this:

let num = "12345678901234567"
if GeneralFunctions.isValidMobileNumber(str: num) {
    return true
} else {
    return false
}

Solution

  • Your current regular expression will check only whether the string ends with the given pattern. If there are, for example, 20 digits, there will be a match because the string still ends with 16 digits. You need to prefix your regular expression with a ^ to match the whole string.

    static func isValidMobileNumber(str: String) -> Bool {
        return str.range(of: "^\\d{3,16}$", options: .regularExpression) != nil
    }