3

How can I replace only a part of a matched regex string ? I need to find some strings that are inside of some brackets like < >. In this example I need to match 23 characters and replace only 3 of them:

string input = "<tag abc=\"hello world\"> abc=\"whatever\"</tag>";
string output = Regex.Replace(result, ???, "def");
// wanted output: <tag def="hello world"> abc="whatever"</tag>

So I either need to find abc in <tag abc="hello world"> or find <tag abc="hello world"> and replace just abc. Do regular expressions or C# allow that ? And even if I solve the problem differently is it possible to match a big string but replace only a little part of it ?

Bitterblue
  • 13,162
  • 17
  • 86
  • 124
  • 3
    Would something like `string result = Regex.Replace(input, @"( – Marc Gravell Nov 06 '13 at 10:15
  • @MarcGravell Ok, I'll keep that in mind. I will not go further than the little modifications I want to apply to the strings. I also know that my input strings will have a very low complexity. – Bitterblue Nov 06 '13 at 10:34

3 Answers3

1

I'd have to look up the #NET regex dialect, but in general you want to capture the parts you don't want to replace and refer to them in your replacement string.

string output = Regex.Replace(input, "(<tag )abc(=\"hello world\">)", "$1def$2");

Another option would be to use lookaround to match "abc" where it follows "<tag " and precedes "="hello world">"

string output = Regex.Replace(input, "(?<=<tag )abc(?==\"hello world\")", "def");
SQB
  • 3,926
  • 2
  • 28
  • 49
0

Instead of Regex.Replace use Regex.Match, then you can use the properties on the Match object to figure out where the match occurred.. then the regular string functions (String.Substring) can be used to replace the bit you want replaced.

Sam Axe
  • 33,313
  • 9
  • 55
  • 89
0

Working sample with named groups:

string input = @"<tag abc=""hello world""> abc=whatever</tag>";
Regex regex = new Regex(@"<(?<Tag>\w+)\s+(?<Attr>\w+)=.*?>.*?</\k<Tag>>");
string output = regex.Replace(input, match => 
{
    var attr = match.Groups["Attr"];
    var value = match.Value;
    var left = value.Substring(0, attr.Index);
    var right = value.Substring(attr.Index + attr.Length);
    return left + attr.Value.Replace("abc", "def") + right;
});
SlavaGu
  • 817
  • 1
  • 8
  • 15