简体   繁体   English

使用JavaScript中的正则表达式精确匹配字符串

[英]Exact match a string using Regular Expression in JavaScript

I want to validate a string in JavaScript to allow alphanumerics, "(", ")" , and spaces. 我想验证JavaScript中的字符串以允许字母数字,“(”,“)”和空格。 So test strings are: 因此测试字符串为:

s1 = "This $h00l*&^ not w0rk342*_(&, <and> always fail" 
s2 = "This should work (ABC1234)"

my code: 我的代码:

var regX = new RegExp(/A-Za-z0-9\\(\\)\\x20+/);
if(!regX.test(s1)){
    alert("InValid value.");
}

But it fails for both the strings. 但是对于两个字符串都失败。

Also as test() function evaluates the matches in the string and not the whole string https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test 同样作为test()函数评估字符串而不是整个字符串中的匹配项https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

Can someone please help. 有人可以帮忙吗? Thanks in advance 提前致谢

You should use this regex: 您应该使用此正则表达式:

/^[A-Za-z0-9() ]*$/

Replace * with + if you don't want to allow empty string. 如果您不希望使用空字符串,请用+替换*

^ and $ test for beginning and the end of the string respectively. ^$测试字符串的开头和结尾。

* means repeat 0 or more times. *表示重复0次或更多次。 + means repeat once or more. +表示重复一次或多次。

To specify a character class (ie a set of character), you need to place the characters inside [] . 要指定一个字符类(即一组字符),您需要将这些字符放在[]


To further shorten the regex: 要进一步缩短正则表达式:

/^[a-z\d() ]*$/i

i flag will make the regex matches case-insensitively, which remove the needs to specify AZ . i标志将使正则表达式不区分大小写地匹配,从而消除了指定AZ的需要。

\\d is the shorthand character class for digits 0-9 . \\d是数字0-9的速记字符类。 Shorthand character class can also be included inside character class. 速记字符类也可以包含在字符类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM