javascript RegExp.test 不工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6793747/
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
RegExp.test not working?
提问by user424134
I am trying to validate year using Regex.test in javascript, but no able to figure out why its returning false.
我试图在 javascript 中使用 Regex.test 验证年份,但无法弄清楚为什么它返回 false。
var regEx = new RegExp("^(19|20)[\d]{2,2}$");
regEx.test(inputValue)
returns false for input value 1981, 2007
regEx.test(inputValue)
为输入值 1981, 2007 返回 false
Thanks
谢谢
回答by BoltClock
As you're creating a RegExp
object using a string expression, you need to double the backslashes so they escape properly. Also [\d]{2,2}
can simply be condensed to \d\d
:
当您RegExp
使用字符串表达式创建对象时,您需要将反斜杠加倍,以便它们正确转义。也[\d]{2,2}
可以简单地浓缩为\d\d
:
var regEx = new RegExp("^(19|20)\d\d$");
Or better yet use a regex literal to avoid doubling backslashes:
或者更好的是使用正则表达式来避免双反斜杠:
var regEx = /^(19|20)\d\d$/;
回答by Mrchief
Found the REALissue:
发现真正的问题:
Change your declaration to remove quotes:
更改您的声明以删除引号:
var regEx = new RegExp(/^(19|20)[\d]{2,2}$/);
回答by Mike C
Do you mean
你的意思是
var inputValue = "1981, 2007";
If so, this will fail because the pattern is not matched due to the start string (^) and end string ($) characters.
如果是这样,这将失败,因为由于开始字符串 (^) 和结束字符串 ($) 字符导致模式不匹配。
If you want to capture both years, remove these characters from your pattern and do a global match (with /g)
如果您想捕获这两年,请从您的模式中删除这些字符并进行全局匹配(使用 /g)
var regEx = new RegExp(/(?:19|20)\d{2}/g);
var inputValue = "1981, 2007";
var matches = inputValue.match(regEx);
matches will be an array containing all matches.
匹配将是一个包含所有匹配项的数组。
回答by Luke
I've noticed, for reasons I can't explain, sometimes you have to have two \\ in front of the d.
我注意到,出于我无法解释的原因,有时您必须在 d 前面有两个 \\。
so try [\\d] and see if that helps.
所以尝试 [\\d] 看看是否有帮助。