开发者

javascript regular expression match() result

开发者 https://www.devze.com 2023-04-12 10:43 出处:网络
Here is what I put into Chrome\'s browser console >> \'abc,de.fg\\nhi\'.match(/.*/g) [\"abc,de.fg\", \"\", \"hi\", \"\"]

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

精彩评论

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