开发者

javascript regular expression match() result

Here is what I put into Chrome's browser console

>> 'abc,de.fg\nhi'.match(/.*/g)
["abc,de.fg", "", "hi", ""]

Why are there empty strings in the result?

A separate question:

>> 'abc\ndef\n'.match(/(.*)\n/)
["abc
", "abc"]
>> 'abc\ndef\n'.match(/.*\n/)
["abc
"]

Why does the first one give two values? I cannot find any documentation that indicates groups (parentheses) should be appended to match resul开发者_如何学Pythonts. This does not occur when using the /g modifier.


About your second question, if there are groups present the result array contains the whole match in the position zero and the group matches in subsequent positions.


The * in your regular expression matches zero or more characters. The . matches anything except a new line. Therefore, it gets split on the newline and matches the empty space before and after.

'abc,de.fg\nhi'.match(/.+/g)
["abc,de.fg", "hi"]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜