开发者

Metacharacters and parenthesis in regular expressions

Can anyone elaborate/translate this regular expression into English?

Thank you.

var g = "123456".match(/(.)(.)/);

I have noticed that the output looks like this:

12,1,2

and I know that dot means any character exc开发者_JAVA百科ept new line. But what does this actually do?


A pair of parenthesis (without a ? as the first character, indicating other behaviour) will capture the contents to a group.

In your example, the first item in the array is the entire match, and subsequent items are any group matches.

It might be clearer if your code was something like:

var g = "123456".match(/.(.).(.)./);

This will match five characters, placing the second and fourth into groups 1 and 2 respectively, so outputting 12345,2,4

If you want pure grouping without capturing the content, use (?:...) syntax, the ?: part indicating a non-capturing group. (There are various assorted group things, like lookaheads and other fun stuff.)

Let me know if that is clear, or would further explanation help?


It looks for two characters - any characters because of the dots - and 'captures' them so that you can look for the whole string that was matched, and for each of the substrings (captures) as well.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜