regex.test V.S.string.match 了解字符串是否与正则表达式匹配 [英] regex.test V.S. string.match to know if a string matches a regular expression

查看:26
本文介绍了regex.test V.S.string.match 了解字符串是否与正则表达式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多时候我使用字符串 match 函数来知道一个字符串是否与正则表达式匹配.

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.测试( String )

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

Executes the search for a match between a regular expression and a specified string. Returns true or false.

string.匹配( RegExp )

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

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 的计算结果为 false

Since null evaluates to 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.在使用 g 全局标志时,使用 .match 检索所有匹配项.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆