Home > Enterprise >  Is it possible to use the backreference of match result as a match of another capture group?
Is it possible to use the backreference of match result as a match of another capture group?

Time:06-15

I have the following string fragments where I want to match the contents of the key attribute and replace all it's occurrences with ***:

name="prefix1 - key_string suffix1" displayName="prefix1 - key_string suffix2" key="key_string" name2="prefix2 - key_string suffix1" desc="prefix1 - key_string suffix1"

I can easily match the attribute value key_string with something like (?<=key=")\b([^"] ) and replace it with *** so it will read like key="***", but can't seem to figure out how to replace other key_string occurrences using backreference.

Is it possible or do I need to split this into 2 regex passes: 1 to get the match result and another to replace the occurrences of match result?

CodePudding user response:

It is not possible to find a string between double quotes after key= string and then replace all occurrences of the found match in the whole input string using a single Regex.Replace operation.

This would imply saving the value to some buffer, then seek to the string beginning point and re-scan the whole input string. This is not possible since regular expression engine searches from left to right (by default) or from right to left (with the RegexOptions.RightToLeft option) but never allows to re-wind to the string start scan position.

The closest pattern would be (?<=key=\"([^\"] )\".*)\1|(?=.*key=\"([^\"] )\".*)\2 (see its demo online) but it is useless as the found match will remain, as it is the "pivot" for all matches (if it is removed before, the lookarounds will not match, and it cannot be remove later as the regex index will be long past the match).

So, use a two-step approach like

var match = Regex.Match(text, @"\bkey=""([^""] )""")?.Groups[1].Value;
if (!string.IsNullOrEmpty(match)
{
    sentence = sentence.Replace(match, ""); // If you just want to remove the found match anywhere inside the string
}
  • Related