需要正则表达式以允许最多3个特殊字符

Need regular expression to allow maximum of 3 special character

本文关键字:许最多 3个 特殊字符 正则表达式      更新时间:2023-09-26

我需要一个满足以下要求的正则表达式。

  1. 应接受长度在0到50个字符之间的字母数字
  2. 应接受除","之外的所有特殊字符
  3. 应接受最少0个、最多3个特殊字符

尝试过这个,但没有按预期工作。

^[a-z's]{0,50}[.'-']*[a-z's]{0,50}[.'-']*$

如果有人做对了,请告诉我。

好吧,你可以写一些可怕的正则表达式,这将是不可能读取或维护的,或者只写代码,说明规则是什么:

function validate(str) {
    var not_too_long          = str.length <= 50,
        has_no_dots           = !/'./.test(str),
        not_too_many_specials = (str.match(/[^'w's]/g) || []).length <= 3;
    return not_too_long && has_no_dots && not_too_many_specials;
}

根据您对"特殊字符"的定义进行适当调整。