-3

这是我想出的,但它也接受;. 有人可以帮助我了解我所缺少的吗

var VALID_ALPHANUMERIC_WITH_SPECIAL_CHARS = /^(?=.*[0-9])|(?=.*[a-zA-Z])([a-zA-Z0-9]|[@#!%*&_\/.:{}\[\]\$\-\=\?\\\(\)\+\~\`\^\<\>])+$/;

谢谢

4

4 回答 4

1

如果您想检查至少有一个字母数字字符,并允许在文本中使用字母数字 + 一些特殊字符,那么下面的正则表达式应该可以工作。我还冒昧地删除了一些不必要的转义。

/^(?=.*[A-Za-z0-9])[a-zA-Z0-9@#!%*&_\/.:{}\[\]$=?\\()+~`^<>-]+$/

在某些地方可以进一步简化,但为了清楚起见,我不理会它们。

于 2013-01-27T13:20:12.233 回答
1

@nhahtdh has already provided a correct regex for you. If you want to understand why your regex failed, let's take a look at it:

^(?=.*[0-9])   # Either anchor the match at the start and assert
               # that there is at least one ASCII digit
|              # OR
               # Assert that there is
(?=.*[a-zA-Z]) # at least one ASCII letter, then match
([a-zA-Z0-9]|[special chars...])+ # one or more of these characters
$              # with an unnecessary alternation; anchor the match to the end

Do you see the problems?

于 2013-01-27T13:47:13.733 回答
0

这部分(?=.*[a-zA-Z])匹配任何后跟一个字母的字符,所以它匹配;a

您可以这样做(?=[^;]*[a-zA-Z])以匹配任何字符,但;

于 2013-01-27T13:37:41.757 回答
0

如果您想接受特殊字符,但;只有一个字母数字字符

var re = /^[@#!%*&_\/.:{}\[\]$\-=?\\()+~`^<>]*[a-zA-Z0-9][@#!%*&_\/.:{}\[\]$\-=?\\()+~`^<>]*$/;

如果您想要除至少一个字母数字字符以外;的特殊字符

var re = /^[a-zA-Z0-9@#!%*&_\/.:{}\[\]$\-=?\\()+~`^<>]*[a-zA-Z0-9][a-zA-Z0-9@#!%*&_\/.:{}\[\]$\-=?\\()+~`^<>]*$/;

JSFiddle用于测试。

于 2013-01-27T13:27:13.507 回答