Pattern with Regex

How to Replace by Pattern with Regex in C#

The correct way of doing what you need is to capture the part you need to keep and only match what you need to replace:

var result = Regex.Replace(s, “(#[A-Za-z0-9]+)=\”\””, “$1???”);
See the regex demo.

In the (#[A-Za-z0-9]+)=”” pattern, the # and alphanumeric chars are captured into Group 1 and later are re-inserted into the resulting string with the help of the replacement backreference $1 (also called a placeholder for Group 1). Since =”” is a string of a known length, you may safely put three ? chars after the $1.

If you have no control over the pattern and just need to replace the contents of the first group, and in case you do not know the length of Group 2 value (it is not the case, but let’s generalize), you may consider the following approach:

var s = “#Abc=\”\””;
var result = Regex.Replace(s, “#[A-Za-z0-9]+(=\”\”)”, m=>
m.Value.Substring(0, m.Groups[1].Index), // Get the substring up to Group 1 value
new string(‘?’, m.Groups[1].Length), // Build the string of Group 1 length ?s
m.Value.Substring(m.Groups[1].Index+m.Groups[1].Length, m.Value.Length-m.Groups[1].Index-m.Groups[1].Length))); // Append the rest of the match



Please enter your comment!
Please enter your name here