Javascript regex.test VS string.match 以了解字符串是否与正则表达式匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10940137/
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
regex.test V.S. string.match to know if a string matches a regular expression
提问by gdoron is supporting Monica
Many times I'm using the string match
function to know if a string matches a regular expression.
很多时候我使用字符串match
函数来知道一个字符串是否与正则表达式匹配。
if(str.match(/{regex}/))
Is there any difference between this:
这有什么区别吗:
if (/{regex}/.test(str))
They seem to give the same result?
他们似乎给出了相同的结果?
回答by gdoron is supporting Monica
Basic Usage
基本用法
First, let's see what each function does:
首先,让我们看看每个函数的作用:
regexObject.test( String)
正则表达式对象。测试(字符串)
Executes the search for a match between a regular expression and a specified string. Returns trueor false.
执行搜索正则表达式和指定字符串之间的匹配项。返回true或false。
string.match( RegExp)
字符串。匹配(正则表达式)
Used to retrieve the matches when matching a string against a regular expression. Returns an array with the matches or
null
if there are none.
用于在将字符串与正则表达式匹配时检索匹配项。返回一个包含匹配项的数组,或者
null
如果没有匹配项。
Since null
evaluates to false
,
由于null
评估为false
,
if ( string.match(regex) ) {
// There was a match.
} else {
// No match.
}
Performance
表现
Is there any difference regarding performance?
性能上有什么区别吗?
Yes. I found this short note in the MDN site:
是的。我在MDN 站点中找到了这个简短的说明:
If you need to know if a string matches a regular expression regexp, use regexp.test(string).
如果您需要知道字符串是否与正则表达式 regexp 匹配,请使用 regexp.test(string)。
Is the difference significant?
差异显着吗?
The answer once more is YES! This jsPerfI put together shows the difference is ~30% - ~60%depending on the browser:
答案再次是肯定的!我放在一起的这个jsPerf显示差异是 ~30% - ~60%取决于浏览器:
Conclusion
结论
Use .test
if you want a faster boolean check. Use .match
to retrieve all matches when using the g
global flag.
使用.test
,如果你想更快的布尔检查。用于.match
在使用g
全局标志时检索所有匹配项。
回答by gtournie
Don't forget to take into consideration the global flag in your regexp :
不要忘记考虑正则表达式中的全局标志:
var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi'); // => true
reg.test('abcdefghi'); // => false <=
This is because Regexp keeps track of the lastIndex when a new match is found.
这是因为当找到新匹配项时,Regexp 会跟踪 lastIndex。