Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
753 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...