为什么正则表达式匹配在 nodejs 中比正常返回更多? [英] Why does a regex match return more than normal in nodejs?

查看:41
本文介绍了为什么正则表达式匹配在 nodejs 中比正常返回更多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在节点 repl 中执行这个指令

If i perform this instruction in the node repl

"hello".match(/(\w+)(.*)/)

它返回这个

[ 'hello',
  'hello',
  '',
  index: 0,
  input: 'hello' ]

我希望它返回前三个项目,其他值从哪里来?

I expected it to return the first three items, where did the other values come from?

推荐答案

  • 数组中的第一项是整个正则表达式匹配项(组 0").那当然是hello.
  • 第二项是第一个捕获组的匹配内容(\w+).又是hello.
  • 第三项是第二个捕获组的匹配内容(.*).这是 hello 之后的空字符串.
  • index 是匹配开始的位置 - 这是字符串的第一个字符.
  • input 显示执行正则表达式的字符串 - 即 hello.
    • The first item in the array is the entire regex match ("group 0"). That's hello, of course.
    • The second item is the content of the first capturing group's match (\w+). That's hello, again.
    • The third item is the content of the second capturing group's match (.*). That's the empty string after hello.
    • index is the position of the start of the match - which is the first character of the string.
    • input shows you the string that the regex was performed on - which is hello.
    • 很难找到这方面的文档(至少对我而言),但 MSDN 中描述了正则表达式匹配返回的对象:http://msdn.microsoft.com/en-us/library/ie/7df7sf4x(v=vs.94).aspx:

      It's surprisingly difficult to find docs on this (at least for me), but here's something from MSDN that describes the object returned by a regex match: http://msdn.microsoft.com/en-us/library/ie/7df7sf4x(v=vs.94).aspx:

      如果没有设置全局标志,match方法返回的数组有两个属性,inputindex.input 属性包含整个搜索字符串.index 属性包含匹配子字符串在完整搜索字符串中的位置.

      If the global flag is not set, the array returned by the match method has two properties, input and index. The input property contains the entire searched string. The index property contains the position of the matched substring within the complete searched string.

      这篇关于为什么正则表达式匹配在 nodejs 中比正常返回更多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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