简体   繁体   English

Regex中是否有一组javascript或任何其他语言的组

[英]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. 我只是在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. 该小组将引用1美元,2美元,3美元和4美元。 I already tried it on my local computer (on firebug) but it gives me results that I can't readily understand. 我已经在我的本地计算机上尝试过它(在firebug上),但它给了我无法理解的结果。 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. 在某些语言中,您可以指定一个标志来说明您希望组所在的顺序。在Javascript中,您无法指定它。 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)) 1) ((name)|(is)|(man))

2) (name) 2) (name)

3) (is) 3) (is)

4) (man) 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. 当达到第一个匹配时,您可以看到匹配组2 (name)的字符串也匹配组1。 Group 3 and 4 didn't match anything. 第3组和第4组没有任何匹配。 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. 在这种情况下,因为组1包装了它将始终包含整个匹配的所有内容,并且因为内部部分是or ,这三个组中只有一个将在每个匹配中包含任何文本。

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

A nested reference is a backreference inside the capturing group that it references, eg (\\1two|(one))+. 嵌套引用是它引用的捕获组内的反向引用,例如(\\ 1two |(one))+。 This regex will give exactly the same behavior with flavors that support forward references. 这个正则表达式将提供与支持前向引用的flavor相同的行为。 Some flavors that don't support forward references do support nested references. 一些不支持前向引用的flavor确实支持嵌套引用。 This includes JavaScript. 这包括JavaScript。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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