regex.test V.S. string.match以了解字符串是否与正则表达式匹配 [英] regex.test V.S. string.match to know if a string matches a regular expression
问题描述
我多次使用字符串匹配
函数来了解字符串是否与正则表达式匹配。
Many times I'm using the string match
function to know if a string matches a regular expression.
if(str.match(/{regex}/))
这是否有任何区别:
if (/{regex}/.test(str))
他们似乎给出相同的结果?
They seem to give the same result?
推荐答案
基本用法
首先,让我们来看看看看每个函数的作用:
Basic Usage
First, let's see what each function does:
regexObject 。 test ( String )
执行正则表达式与指定字符串之间匹配的搜索。返回 true 或 false 。
string 。 匹配 ( RegExp )
用于在将字符串与正则表达式匹配时检索匹配项。返回带有匹配项的数组,如果没有,则返回
null
。
null
评估为 false
,
if ( string.match(regex) ) {
// There was a match.
} else {
// No match.
}
表现
性能方面有什么不同吗?
Performance
Is there any difference regarding performance?
是。我在 MDN网站中找到了这条简短的说明:
Yes. I found this short note in the MDN site:
如果您需要知道字符串是否与正则表达式regexp匹配,请使用regexp.test(string)。
If you need to know if a string matches a regular expression regexp, use regexp.test(string).
差异是否显着?
答案再次是是!我把这个 jsPerf 显示出差异 ~30% - ~60% 取决于浏览器:
The answer once more is YES! This jsPerf I put together shows the difference is ~30% - ~60% depending on the browser:
使用 .test
如果你想要更快的布尔检查。使用 .match
在使用 g
全局标记时检索所有匹配。
Use .test
if you want a faster boolean check. Use .match
to retrieve all matches when using the g
global flag.
这篇关于regex.test V.S. string.match以了解字符串是否与正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!