Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

node.js - Why does a regex match return more than normal in nodejs?

If i perform this instruction in the node repl

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

It returns this

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • 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.

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:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...