简体   繁体   English

正则表达式与预期符号不匹配

[英]Regex doesn't match expected symbols

I have regex to match only digits and some specific symbols. 我有正则表达式只匹配数字和一些特定的符号。 /[()\\-\\+ \\d]/g

I try this regex with regex101.com and it match all expected symbols. 我用regex101.com尝试了此正则表达式,它与所有预期符号匹配。

In my app i use this regex to check if user input into textbox only allowed symbols. 在我的应用程序中,我使用此正则表达式检查用户在文本框中的输入是否仅允许使用符号。 And here is problem as only digits, space and () are allowed according to regex. 这是问题,因为根据正则表达式只允许数字,空格和()

My code : http://jsfiddle.net/r6e8axsr/ 我的代码: http : //jsfiddle.net/r6e8axsr/

You need to anchor the regex to the start and end of the string, and allow more than a single character to match. 您需要将正则表达式锚定到字符串的开头和结尾,并允许多个字符匹配。 If you don't, the regex will succeed as long as there is at least one of the allowed characters in your string. 如果不这样做,只要字符串中至少有一个允许的字符,则正则表达式将成功。

if (/^[()+ \d-]*$/.test(subject)) {
    // Successful match
} else {
    // Match attempt failed
}

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

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