Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use $1 in regex_replace?

From reading the FCD for regex_replace (28.11.4) I can only guess that the function can also use parts of the original string for replacing? I can not test it with my gcc, is this correct?

using namespace std;
regex rx{ R"((\d+)-(\d+))" }; // regex: (\d+)-(\d+)
cout << regex_replace("123-456", rx, "b: $2, a:$1");
// "b: 456, a:123"

As you can see, I assume $1 and $2 refer to the "()" capturing groups (and not \1 and \2 like elsewhere).

Update. So, I guess this is a two-part question

  • Is this use of capturing groups in the replacement text supported at all?
  • Is the default ECMAScript syntax using $n? Or \n?
like image 241
towi Avatar asked Oct 11 '11 07:10

towi


People also ask

What does $1 do in regex?

The $ number language element includes the last substring matched by the number capturing group in the replacement string, where number is the index of the capturing group. For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

What is $1 in replace Javascript?

In your specific example, the $1 will be the group (^| ) which is "position of the start of string (zero-width), or a single space character". So by replacing the whole expression with that, you're basically removing the variable theClass and potentially a space after it.

What is $1 and $2 in Javascript?

In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.


1 Answers

Table 139 in the C++ 2011 FDIS lists two constants that can be used to affect the rules used for the format string in regex_replace, format_default and format_sed. format_default is described as using "the rules used by the ECMAScript replace function in ECMA-262, part 15.5.4.11 String.prototype.replace." This standard does indicate the use of $ for backreferences. See: ECMA-262

Using the format_sed flag instead uses the rules for the sed utility in POSIX. Sed doesn't appear to support $ backreferences.

like image 88
bames53 Avatar answered Oct 01 '22 08:10

bames53