1

I would like to write a regex expression that will seek for this pattern: asdf=123 and then once something is found in a file/string, it should just replace the 123 part to bbbcccddd.

How can I do that in C# ?

greenfeet
  • 677
  • 1
  • 7
  • 27
dev hedgehog
  • 8,698
  • 3
  • 28
  • 55
  • 3
    Might this link help? : https://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx – Danny Sullivan Jul 10 '15 at 07:54
  • More details please. What is after/before "asdf=123" in your string / file? If it's something like "asdasd____ asdf=123_____asdasd" it's one thing but if it's " zzzzzzasdf=12309656097" - is something different. It'd be nice if you provide shortened example of this string. Values are fixed ? Or it's just an example of pattern you're looking for ? – Fabjan Jul 10 '15 at 08:17

3 Answers3

2
Console.WriteLine(Regex.Replace("11asdf=123 ttt", @"(?<=asdf=)123", "321"));

Though I write this code,but I think there will many problem because you don't describe your problem clearly,like if there some character not white before asdf,or there is some number after 123,do you still want to replace 123?

Sky Fang
  • 1,101
  • 6
  • 6
1
string pattern = @"asdf=123";
var result = Regex.Replace(yourString, pattern, "asdf=bbbcccddd");
greenfeet
  • 677
  • 1
  • 7
  • 27
  • For such approach regex is overkill, just string.Replace will be enough https://msdn.microsoft.com/en-us/library/fk49wtc1(v=vs.110).aspx – Stanislav Berkov Jul 10 '15 at 08:11
0

You could do something like so:

string pattern = "asdf=123";
Regex r = new Regex(@"(.*?=)(.*)");
Match m = r.Match(pattern);
if(m.Success)            
      Console.WriteLine(m.Groups[1].Value + new String(m.Groups[2].Value.Reverse().ToArray()));

The above will match anything till it finds an equals ((.*?=)) and places it in a group. It will then match what follows and places it in another group ((.*)). The first group is then printed as is while the content of the second group is reversed.

A less verbose but less flexible way of doing this would be to use Regex.Replace, with something like so:

   string pattern = "asdf=123";
   Console.WriteLine(Regex.Replace(pattern, @"(.*?=)(\d)(\d)(\d)", "$1$4$3$2"));

This is less robust though since you would need to know the amount of digits before hand.

EDIT: As per your edit:

You will need to use: Regex.Replace("asdf=123", "(.*?=)\d{3}","$1bbbcccddd")

npinti
  • 51,780
  • 5
  • 72
  • 96