Javascript 用字母数字、空格和标点符号匹配字符串的正则表达式

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

A regex to match strings with alphanumeric, spaces and punctuation

javascriptregex

提问by jdimona

I need a regular expression to match strings that have letters, numbers, spaces and some simple punctuation (.,!"'/$). I have ^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$and it works well for alphanumeric and spaces but not punctuation. Help is much appreciated.

我需要一个正则表达式来匹配包含字母、数字、空格和一些简单标点符号 ( .,!"'/$) 的字符串。我有^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$,它适用于字母数字和空格,但不适用于标点符号。非常感谢帮助。

回答by CaNNaDaRk

Just add punctuation and other characters inside classes (inside the square brackets):

只需在类内(方括号内)添加标点符号和其他字符:

[A-Za-z0-9 _.,!"'/$]*

This matches every string containing spaces, _, alphanumerics, commas, !, ", $, ... Pay attention while adding some special characters, maybe you need to escape them: more info here

这匹配每个包含空格、_、字母数字、逗号、!、"、$、...的字符串,在添加一些特殊字符时要注意,也许你需要对它们进行转义:更多信息在这里

回答by Tim Pietzcker

Assuming from your regex that at least one alphanumeric character must be present in the string, then I'd suggest the following:

假设根据您的正则表达式,字符串中必须至少存在一个字母数字字符,那么我建议如下:

/^(?=.*[A-Z0-9])[\w.,!"'\/$ ]+$/i

The (?=.*[A-Z0-9])lookahead checks for the presence of one ASCII letter or digit; the nest character class contains all ASCII alphanumerics including underscore (\w) and the rest of the punctuation characters you mentioned. The slash needs to be escaped because it's also used as a regex delimiter. The /imodifier makes the regex case-insensitive.

(?=.*[A-Z0-9])先行检查一个ASCII字母或数字的存在; 嵌套字符类包含所有 ASCII 字母数字,包括下划线 ( \w) 和您提到的其余标点符号。斜线需要转义,因为它也用作正则表达式分隔符。该/i修改使正则表达式不区分大小写。

回答by Tarun Gupta

<script type="text/javascript">
check("hello dfdf asdjfnbusaobfdoad fsdihfishadio fhsdhf iohdhf");
function check(data){
var patren=/^[A-Za-z0-9\s]+$/;
    if(!(patren.test(data))) {
       alert('Input is not alphanumeric');       
       return false;
    }
    alert(data + " is good");
}
</script>