匹配正则表达式中的特殊字符和字母 [英] Matching special characters and letters in regex
问题描述
我正在尝试验证字符串,该字符串应仅包含字母数字和特殊字符& -._
。为此,我尝试使用正则表达式。
I am trying to validate a string, that should contain letters numbers and special characters &-._
only. For that I tried with a regular expression.
var pattern = /[a-zA-Z0-9&_\.-]/
var qry = 'abc&*';
if(qry.match(pattern)) {
alert('valid');
}
else{
alert('invalid');
}
使用上面的代码时,字符串 abc& *
有效。但我的要求是显示这个无效。即每当字母,数字或特殊字符& -._
以外的字符出现时,该字符串应评估为无效。我怎么能用正则表达式做到这一点?
While using the above code, the string abc&*
is valid. But my requirement is to show this invalid. ie Whenever a character other than a letter, a number or special characters &-._
comes, the string should evaluate as invalid. How can I do that with a regex?
推荐答案
将它们添加到允许的字符中,但您需要转义它们中的一些,例如 - ] / \
Add them to the allowed characters, but you'll need to escape some of them, such as -]/\
var pattern = /^[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/
这样你就可以删除你想要禁止的任何个人角色。
That way you can remove any individual character you want to disallow.
此外,你想要包含一个开头字符串位置标记符结束^和$
Also, you want to include the start and end of string placemarkers ^ and $
更新:
正如elclanrs所理解的那样(而我们其他人最初没有),在模式中需要允许的仅特殊字符是& -._
As elclanrs understood (and the rest of us didn't, initially), the only special characters needing to be allowed in the pattern are &-._
/^[\w&.\-]+$/
[\ w]与[a-zA-Z0-9 _]
[\w] is the same as [a-zA-Z0-9_]
相同虽然破折号不需要转义列表的开头或结尾,我更喜欢这样做,以防其他字符被添加。另外,+ m eans你需要至少一个列出的字符。如果零是好的(即一个空值),然后用*代替它:
Though the dash doesn't need escaping when it's at the start or end of the list, I prefer to do it in case other characters are added. Additionally, the + means you need at least one of the listed characters. If zero is ok (ie an empty value), then replace it with a * instead:
/^[\w&.\-]*$/
这篇关于匹配正则表达式中的特殊字符和字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!