Is there a way to modify the value of a backreference?
Example:
In the following Text
"this is a test"
the word ‘test’ should be extracted and inserted into another text via backrefrence.
Regex:
(test)
Replacement:
"this is another \1"
That works fine so far. But now the question is, if it is possible to modify the backreference before inserting. Something like converting the word “test” to uppercase.
I think it could look like:
"this is another \to_upper\1"
Is there something defined in the “standard” (is there any standard at all?) of Regular Expressions?
Many implementations (javascript, python etc) let you specify a function as the replace parameter. The function normally takes the whole matched string, its position in the input string, and the captured groups as arguments. The string returned by this function is used as the replacement text.
Here is how to do it using JavaScript: the replace function takes the whole matched substring as its first argument, value of captured groups as the next n arguments, followed by the index of the matched string in the original input string and the whole input string.
ouput:
And here is the python version – it even gives you start/end values for each group:
Output: