简体   繁体   中英

Is there a group of groups in Regex in javascript or any other language

I was just playing with the native replace method for strings in javascript. Is there any thing like groups of groups. If not, how are groups ordered in string where a group encapsulates other open and closed parentheses (potential groups). For example,

var string = "my name is name that is named man".replace(/((name)|(is)|(man))/g, "$1");

What will the group references $1, $2, $3, and $4 be. I already tried it on my local computer (on firebug) but it gives me results that I can't readily understand. A clear explanation on this will be appreciated!!

In some languages you can specify a flag to say the order you want the groups to be in. In Javascript you can't specify it. They will be in the order that the opening parenthesis occur in. So in your above example the groups will be, in order:

1) ((name)|(is)|(man))

2) (name)

3) (is)

4) (man)

To see the output more clearly from your above string, execute:

"my name is name that is named man".replace(/((name)|(is)|(man))/g, '1($1) 2($2) 3($3) 4($4)\n');

Then you can cleary see what's in each group when each match is reached:

"my 1(name) 2(name) 3() 4()
 1(is) 2() 3(is) 4()
 1(name) 2(name) 3() 4()
 that 1(is) 2() 3(is) 4()
 1(name) 2(name) 3() 4()
d 1(man) 2() 3() 4(man)"

When the first match is reached you can see that the string which matched group 2 (name) matched group 1 as well. Group 3 and 4 didn't match anything. Same goes for each match. in this case since group one wraps everything it will always contain the whole match, and since the inner part is an or , only one of those three groups will contain any text on each match.

http://www.regular-expressions.info/brackets.html

A nested reference is a backreference inside the capturing group that it references, eg (\\1two|(one))+. This regex will give exactly the same behavior with flavors that support forward references. Some flavors that don't support forward references do support nested references. This includes JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM