【问题标题】:regular expression to avoid only special chars正则表达式以避免仅特殊字符
【发布时间】:2014-04-17 07:10:44
【问题描述】:

我正在验证输入文本框。我是正则表达式的新手。如果输入的所有字符都是特殊字符,我想要一个引发验证错误的表达式。但它应该允许字符串中有特殊字符。

-(**&^&)_) ----> 无效。

abcd-as jasd12 ----> 有效。

目前正在使用/^[a-zA-Z0-9-]+[a-z A-Z 0-9 -]*$/ 验证数字和字母

【问题讨论】:

  • 什么是特殊字符?
  • 您要允许哪些特殊字符?

标签: javascript html regex


【解决方案1】:

/[A-Za-z0-9]/ 如果字符串包含至少 1 个字母或数字,则将匹配正数,这应该与您的要求相同。如果没有字母或数字,则该正则表达式将评估为假。

【讨论】:

  • 你不需要.*
  • 没错。现在正在编辑,不知道我最初在想什么。
  • 这是否允许在其间使用空格和特殊字符??
  • 你传给它一个字符串,它会检查该字符串以确保它在字符串中的任何位置至少包含 1 个字母或数字,而不管其他字符。
【解决方案2】:

根据您的评论,特殊字符为!@#$%^&*()_-,因此您可以使用:

var regex = /^[!@#$%^&*()_-]+$/;
if (regex.test(string)) 
    // all char are special

如果您有更多特殊字符,请将它们添加到字符类中。

【讨论】:

    【解决方案3】:

    使用负前瞻:

    if (/^(?![\s\S]*[^\w -]+)[\s\S]*?$/im.test(subject)) {
        // Successful match
    } else {
        // Match attempt failed
    }
    

    DEMO

    解释:

    ^(?!.[^\w -]+).?$

    Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
    Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!.*[^\w -]+)»
       Match any single character «.*»
          Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
       Match a single character NOT present in the list below «[^\w -]+»
          Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
          A word character (letters, digits, and underscores) «\w»
          The character “ ” « »
          The character “-” «-»
    Match any single character «.*?»
       Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
    Assert position at the end of a line (at the end of the string or before a line break character) «$»
    

    【讨论】:

      【解决方案4】:

      ~[^a-zA-z0-9 ]+~ 如果字符串中不包含至少一个字母、数字和空格,它将匹配。

      Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-13
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多