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
$
n? Or \
n?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.
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.
In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With