我需要一个正则表达式来匹配包含字母,数字,空格和一些简单标点符号的字符串( .,!"'/$
)。我有^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$
它适用于字母数字和空格,但不适用于标点符号。非常感谢帮助。
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
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 /i
modifier makes the regex case-insensitive.
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.