views:

39

answers:

2

Hi all:

What's the intent of () inside the regex? Thanks.

pattern.replace(/\{(\d+)\}/g,
        function(pattern, index) { 
            return args[index].toString(); 
        });

PS: args is something like ["3", "dl1", "42"]

+2  A: 

It creates a group.

What is args?

Confluence
something like ["3", "dl1", "42"]
Ricky
Hi, what's the purpose to create groups here?
Ricky
+4  A: 

It is used to manage grouping.

The purpose of grouping is to make backreferences on searches & replaces. Using regex you can make that Jhon Doe becomes Doe, Jhon.

To achieve that, you would use a Regex (\w*) (\w*) with two grups, and replace it for $2, $1

Usually, the first group (0) references the whole match of the regex, being the other groups numbered according to the order where they are in your expression.

SoulWanderer
+1: But I would add that not all groups are capturing groups. Some just affect the operation of *,+,?,| etc
CurtainDog
Hi can u make a example for your answer? Thanks.
Ricky
I use a regex (Java format, it is quite similar to Javascript) to parse jdbc oracle connection chain:`jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=test)(PORT=1521))(CONNECT_DATA=(SID = sidbbdd))`I need it to fin the host, so I would write`.*@.*HOST=(\w*)\).*`This regex will ignore pretty much everything until it finds `HOST=` then, it will find everything until it finds `)` and ignore the rest of the chain.To reference the part of my host I would use $1, which would return `test`.
SoulWanderer
Should I need further matchings of subsets of the regex, I would use more groups, for instance`(.*@.*)HOST=(\w*)\)(.*)`would return:$0 --> `jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=test)(PORT=1521))(CONNECT_DATA=(SID = sidbbdd))`$1 --> `jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(`$2 --> `test`$3 --> `(PORT=1521))(CONNECT_DATA=(SID = sidbbdd))`
SoulWanderer
(sorry about formatting)
SoulWanderer
@SoulWanderer: Thanks
Ricky