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
}
2
  • 2
    I guess you are missing starting ^? Anyway, you have to define "it is not working". How do you test it? Commented Nov 10, 2022 at 7: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. Commented Nov 10, 2022 at 7:27

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Just mentioning: There is also the .anchored option which (like ^) limits the search to the start of the string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.