代码之家  ›  专栏  ›  技术社区  ›  AndreKR

Javascript正则表达式是否包含隐式^?

  •  0
  • AndreKR  · 技术社区  · 14 年前

    我认为两个例子的结果应该是相同的(“0”),但事实并非如此。为什么?

    "0 Y".match(/[0-9]*/) // returns "0"
    
    "Y 0".match(/[0-9]*/) // returns ""
    
    3 回复  |  直到 14 年前
        1
  •  0
  •   kennytm    14 年前

    不,没有隐含的 ^ . 但是,开头的空字符串与regex匹配 /[0-9]*/ ,所以 "" 被退回。

    您可以查看匹配过程(没有 /g 旗子)像这样:

    for (cursor in [0, 1, .. string.length-1])
      if (the regex matches string.substr(cursor) with an implicit '^')
         return the match;
    return null;
    
    "0 Y" -> find longest match for [0-9]* from the current cursor index (beginning)
          -> found "0" with * = {1}
          -> succeed, return.
    
    "Y 0" -> find longest match for [0-9]* from the current cursor index (beginning)
          -> found "" with * = {0}
          -> succeed, return.
    

    因此,应避免使用与空字符串匹配的正则表达式。如果您确实需要一个数字来匹配,请使用 + .

    "0 Y".match(/\d+/)
    
        2
  •  4
  •   mikerobi    14 年前

    不,它没有隐含的 ^ .

    * 表示匹配零个或多个字符,因为字符串开头有零位数字,所以匹配并返回空字符串。

        3
  •  2
  •   Nick Craver    14 年前

    我想你想要的是:

    "0 Y".match(/[0-9]/) // returns "0"
    
    "Y 0".match(/[0-9]/) // returns "0"
    

    你的电流 * 版本与0匹配 或更多 数字…所以空字符串是匹配项。以这个为例,可以获得更清晰的视图:

    "Y 0".match(/[0-9]*/g) // matches: "", "0", ""