Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape capture group $N followed by integer when performing JavaScript regular expression replace?

I understand that in JavaScript, you can perform regular expression replace with reference to capture groups like this:

> "Hello World 1234567890".replace(
        /Hello (World) (1)(2)(3)(4)(5)(6)(7)(8)(9)(0)/,
        "What's up $1");
"What's up World"

Which is all good. But what if I want to reference to group 1 then immediately followed by "1". Say I what to see "What's up World1". So I'd write:

> "Hello World 1234567890".replace(
        /Hello (World) (1)(2)(3)(4)(5)(6)(7)(8)(9)(0)/,
        "What's up $11");
"What's up 0"

Of course, in this case, it's referencing to group 11, which is "0", instead of group 1 followed by "1".

How could I resolve this ambiguity?

like image 611
initialxy Avatar asked Nov 07 '13 17:11

initialxy


People also ask

How do I reference a capture group in regex?

If your regular expression has named capturing groups, then you should use named backreferences to them in the replacement text. The regex (?' name'group) has one group called “name”. You can reference this group with ${name} in the JGsoft applications, Delphi, .

How do I capture two groups in regex?

They are created by placing the characters to be grouped inside a set of parentheses ( , ) . We can specify as many groups as we wish. Each sub-pattern inside a pair of parentheses will be captured as a group. Capturing groups are numbered by counting their opening parentheses from left to right.

What is capturing group in regex Javascript?

Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. Backreferences refer to a previously captured group in the same regular expression.

What is non capturing group in regex?

Non-capturing groups are important constructs within Java Regular Expressions. They create a sub-pattern that functions as a single unit but does not save the matched character sequence. In this tutorial, we'll explore how to use non-capturing groups in Java Regular Expressions.


1 Answers

You can use String#replace with a callback function argument:

str = "Hello World 1234567890";
repl = str.replace(/Hello (World) (1)(2)(3)(4)(5)(6)(7)(8)(9)(0)/, function(r, g) {
      return "What's up " + g + '1';});

//=> What's up World1
like image 196
anubhava Avatar answered Oct 14 '22 14:10

anubhava