zoukankan      html  css  js  c++  java
  • regex.test V.S. string.match to know if a string matches a regular expression

    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}/))
    

    Is there any difference between this:

    if (/{regex}/.test(str))
    

    They seem to give the same result?

    回答

    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 true or 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.

    Since null evaluates to 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:

    If you need to know if a string matches a regular expression regexp, use regexp.test(string).

    Is the difference significant?

    The answer once more is YES! This jsPerf I put together shows the difference is ~30% - ~60% depending on the browser:

    Conclusion

    Use .test if you want a faster boolean check. Use .match to retrieve all matches when using the g global flag.

    回答2

    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.

    同一个字符串,第二次test的时候,会从上一次相同字符串匹配的结束位置开始匹配

  • 相关阅读:
    js字符串分割
    Maven打包出错Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test
    Kafka
    linux 切换PHP版本
    linux 查看服务状态及开发端口
    php消息队列
    windows 设置composer 淘宝镜像
    PHP使用CURL详解
    linux php7.0 安装redis扩展
    linux 快速查找安装目录方法
  • 原文地址:https://www.cnblogs.com/chucklu/p/14217667.html
Copyright © 2011-2022 走看看