javascript jquery中字母数字和特殊字符的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8411001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex for alphanumeric and special characters in jquery
提问by jogesh_pi
i tried to make a regex for my Address column the code is:
我试图为我的地址列创建一个正则表达式,代码是:
var str = "97sadf []#-.'";
var regx = /^[a-zA-z0-9\x|]|[|-|'|.]*$/;
if(str.match(regx))
document.write('Correct!');
else
document.write('Incorrect!');
the special character i want that is ][#-.
the given code return me the correct match but if i add another kind of the special character like @%
then the correct result i got, but i want the incorrect result.
我想要的特殊字符是][#-.
给定的代码,返回正确的匹配,但如果我添加另一种特殊字符,就像@%
我得到的正确结果,但我想要不正确的结果。
i don't know where i did wrong please help me to make right..
我不知道我哪里做错了请帮我改正..
EDIT: Sorry guys but the one thing i have to discuss with you that is there is no necessary to enter the special characters that i mentioned ][#-.
, but if the someone enter other then the given special character then should return the incorrect.
编辑:对不起,伙计们,但我必须与你们讨论的一件事是没有必要输入我提到的特殊字符][#-.
,但是如果有人输入其他给定的特殊字符,则应该返回不正确的字符。
回答by mynameiscoffey
The correct regex (assuming you want uppercase letters, lowercase letters, numbers, spaces and special characters [].-#'
) is:
正确的正则表达式(假设您需要大写字母、小写字母、数字、空格和特殊字符[].-#'
)是:
var regx = /^[a-zA-Z0-9\s\[\]\.\-#']*$/
There are a couple things breaking your code.
有几件事会破坏您的代码。
First, [
, ]
, -
and .
have special meaning, and must be escaped (prefixed with \
).
首先, [
, ]
, -
and.
有特殊含义,必须转义(以 为前缀\
)。
\x
checks for line breaks, where we want spaces (\s
).
\x
检查换行符,我们需要空格 ( \s
)。
Next, lets look at the structure; for simplicity's sake, lets simplify to ^[abc]|[def]*$
. (abc
and def
being your two blocks of character types). Since the *
is attached to the second block, it is saying one instance of [abc]
or any number of [def]
.
接下来,让我们看一下结构;为简单起见,让我们简化为^[abc]|[def]*$
。(abc
并def
成为您的两个字符类型块)。由于*
附加到第二个块,它表示 的一个实例[abc]
或任意数量的[def]
。
Finally, we don't need |
inside of brackets, becuase they already mean one character contained within them (already behaves like an or).
最后,我们不需要|
括号内,因为它们已经表示包含在其中的一个字符(已经表现得像一个或)。