0

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 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

+1: But I would add that not all groups are capturing groups. Some just affect the operation of *,+,?,| etc
Hi can u make a example for your answer? Thanks.
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.
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))
2

It creates a group.

What is args?

2 Comments

something like ["3", "dl1", "42"]
Hi, what's the purpose to create groups here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.