1

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
}
jaytrixz
  • 4,059
  • 7
  • 38
  • 57
  • 2
    I guess you are missing starting `^`? Anyway, you have to define "it is not working". How do you test it? – Sulthan Nov 10 '22 at 07:24
  • By the way, `return str.range(of: "...", options: .regularExpression) != nil` is simpler to write. You don't need `NSRegularExpression` unless you actually need to know the matched patterns. – Sulthan Nov 10 '22 at 07:27

1 Answers1

1

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
}
Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • 2
    Just mentioning: There is also the `.anchored` option which (like `^`) limits the search to the start of the string. – Martin R Nov 10 '22 at 08:42