正则表达式,以避免只有特殊的字符

时间:2014-04-17 07:10:45

标签: javascript html regex

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

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

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

目前正在使用/^[a-zA-Z0-9-]+[a-z A-Z 0-9 -]*$/

验证数字和字母

4 个答案:

答案 0 :(得分:2)

如果字符串包含至少1个字母或数字,

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

答案 1 :(得分:2)

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

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

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

答案 2 :(得分:1)

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

Demo

答案 3 :(得分:1)

使用否定Lookahead:

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) «$»