regex Swift中字符串中最小和最大数字的正则表达式[duplicate]

s4n0splo  于 2022-11-18  发布在  Swift
关注(0)|答案(1)|浏览(107)

此问题在此处已有答案

Make sure regex matches the entire string with Swift regex(3个答案)
7天前关闭。
截至7天前,机构群体正在审查是否重新讨论此问题。
如果一个字符串中的字符数有最小和最大字符数,并且应该是数字而不是字母或符号,那么正则表达式是什么呢?它不需要匹配相同的数字,只需要匹配数字串中的字符数。
我正在使用这个正则表达式模式"\\d{3,16}$",但它不起作用。它只在字符数小于3时起作用,但在字符数大于16时不起作用。
这是我的代码:

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
}

我是这样检查的:

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

kuarbcqp1#

您目前的正则表达式只会检查字串是否以指定的样式结尾。例如,如果有20个数字,就会有相符的字串,因为字串仍然以16个数字结尾。您必须在正则表达式前面加上^,才能符合整个字串。

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

相关问题