【问题标题】:Javascript regex to check for exact alphanumeric and special characters用于检查确切的字母数字和特殊字符的 Javascript 正则表达式
【发布时间】:2020-02-24 16:12:37
【问题描述】:

这些是我需要检查用户输入的特殊字符、数字和字母 如果用户没有按照以下标准输入,则抛出警报消息。

  1. (破折号)
  2. (下划线)
  3. (句号)
  4. (
  5. 空间
  6. )
  7. &
  8. $
  9. #
  10. 数字
  11. 阿尔巴佩特

为此,我在网上的一些文章的帮助下想出了一个正则表达式

我的正则表达式

/^\w\s-.()&$#/  

    -- Here, \w matches letter , digits and underscores
    --       \s matches spaces table and line breaks. 
    --       -  matches the hypen in the character set example [a-z]   

示例——str 被传递为

  1. Name123& ---- 真
  2. 名字 123$ ---- true
  3. Name@@@ ---- False,因为 @ 是不允许的
  4. 名字-._& ---- 真
  5. Name@._&$ --- 错误,因为 @ 是不允许的
  6. Name.[] --- 错误,因为 [] 是不允许的
function checkfirmName(str) {
    var pattern = new RegExp(/^\w\s-.()&$#/); //acceptable char

    if (pattern.test(str)) {
        return true; //good user input
    }

    alert("Please only use \nUnderScore,Dot,(,Space,),&,$,# \nThese are only allowed\n");

    return false;  // bad user input 
}

我也不确定测试扩展是否有效(它返回真假)但不确定它是否遍历并检查每个字符,所以我使用 indexof 找到了另一段代码:

function isValid(str) {
    var iChars = "/^\w\s-.()&$#/";

    for (var i = 0; i < str.length; i++) {
        if (iChars.indexOf(str.charAt(i)) != -1) {
            $.alert("File name has should have special characters \nUnderScore,Dot,(,Space,),&,$,# \nThese are only allowed\n");
            return false;
        }
    }

    return true;
}

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    您可以将此正则表达式与包含所有允许的字符集的字符类一起使用:

    /^[-\w .()&$#]+$/
    

    RegEx Demo

    • 您需要在正则表达式中使用锚点。

    • 未转义的连字符应位于字符类的第一个或最后一个位置。


    另一种方法是查找任何不允许的字符,如果找到则匹配失败:

    function checkfirmName(str) {
        const pattern = /[^-\w .()&$#]/; //not-acceptable char
    
        if (pattern.test(str)) {
            alert("Please only use \nUnderScore,Dot,(,Space,),&,$,# \nThese are only allowed\n");
            return false; // bad user input
        }
    
        return true;  // good user input 
    }
    

    【讨论】:

      【解决方案2】:

      我发现regex101.com 在解释和测试 Python 和 Javascript 的正则表达式方面非常有帮助。根据您的要求,我相信以下内容会很有用,^[-\.\(\) \&amp;$\#\w]+$

      \w:因为它处理所有数字、字母和下划线。

      关于JS,代码可以是这样的

      function isValid(str) {
          var patt = /^[-\.\(\) \&$\#\w]+$/;
          return patt.test(str);
      }
      

      【讨论】:

      • 将 ^ 放入集合中。这将表现为一个否定集。正则表达式应该是/[^-.(\s)&amp;$#\w]/
      • 我添加了插入符号来检查字符串的开头和结尾的美元来检查字符串的结尾。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多