Javascript 匹配正则表达式中的特殊字符和字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13946651/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:13:02  来源:igfitidea点击:

Matching special characters and letters in regex

javascriptregexspecial-characters

提问by Khaleel

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');
}

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?

使用上述代码时,字符串abc&*有效。但我的要求是证明这个无效。即,每当出现字母、数字或特殊字符以外的字符时&-._,该字符串应评估为无效。我怎么能用正则表达式做到这一点?

回答by Highly Irregular

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 $

此外,您希望包含字符串地标 ^ 和 $ 的开始和结束

Update:

更新:

As elclanrs understood (and the rest of us didn't, initially), the onlyspecial characters needing to be allowed in the pattern are &-._

正如 elclanrs 所理解的(我们其他人最初没有理解),模式中唯一需要允许的特殊字符是 &-._

/^[\w&.\-]+$/

[\w] is the same as [a-zA-Z0-9_]

[\w] 与 [a-zA-Z0-9_] 相同

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&.\-]*$/

回答by Ja?ck

Well, why not just add them to your existing character class?

那么,为什么不将它们添加到您现有的字符类中呢?

var pattern = /[a-zA-Z0-9&._-]/

If you need to check whether a string consists of nothing but those characters you have to anchorthe expression as well:

如果您需要检查字符串是否只包含这些字符,您还必须锚定表达式:

var pattern = /^[a-zA-Z0-9&._-]+$/

The added ^and $match the beginning and end of the string respectively.

添加的^$匹配的分别是字符串的开头和结尾。

Testing for letters, numbers or underscore can be done with \wwhich shortens your expression:

可以测试字母、数字或下划线,\w以缩短您的表达式:

var pattern = /^[\w&.-]+$/

As mentioned in the comment from Nathan, if you're not using the results from .match()(it returns an array with what has been matched), it's better to use RegExp.test()which returns a simple boolean:

正如 Nathan 的评论中所提到的,如果您不使用结果.match()(它返回一个包含匹配内容的数组),最好使用RegExp.test()which 返回一个简单的布尔值:

if (pattern.test(qry)) {
    // qry is non-empty and only contains letters, numbers or special characters.
}

Update 2

更新 2

In case I have misread the question, the below will check if all three separate conditions are met.

如果我误读了这个问题,下面将检查是否满足所有三个单独的条件。

if (/[a-zA-Z]/.test(qry) && /[0-9]/.test(qry) && /[&._-]/.test(qry)) {
   // qry contains at least one letter, one number and one special character
}

回答by elclanrs

Try this regex:

试试这个正则表达式:

/^[\w&.-]+$/

Also you can use test.

你也可以使用test.

if ( pattern.test( qry ) ) {
  // valid
}

回答by Amrutha VS

let pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!@#$%^&*]{6,16}$/;

//following will give you the result as true(if the password contains Capital, small letter, number and special character) or false based on the string format

let reee =pattern .test("helLo123@");   //true as it contains all the above

回答by chadalavada harish

Try this RegEx: Matching special charecters which we use in paragraphs and alphabets

试试这个正则表达式:匹配我们在段落和字母表中使用的特殊字符

   Javascript : /^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$/.test(str)

                .test(str) returns boolean value if matched true and not matched false

            c# :  ^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$