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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:40:17  来源:igfitidea点击:

regex.test V.S. string.match to know if a string matches a regular expression

javascriptregexperformance

提问by gdoron is supporting Monica

Many times I'm using the string matchfunction 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.

执行搜索正则表达式和指定字符串之间的匹配项。返回truefalse

string.match( RegExp)

字符串匹配正则表达式

Used to retrieve the matches when matching a string against a regular expression. Returns an array with the matches or nullif there are none.

用于在将字符串与正则表达式匹配时检索匹配项。返回一个包含匹配项的数组,或者null如果没有匹配项。

Since nullevaluates 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%取决于浏览器:

test vs match | Performance Test

测试与匹配 |  性能测试

Conclusion

结论

Use .testif you want a faster boolean check. Use .matchto retrieve all matches when using the gglobal 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。