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# ?

2
  • 3
    Might this link help? : msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx Commented Jul 10, 2015 at 7: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 ? Commented Jul 10, 2015 at 8:17

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

Comments

1
string pattern = @"asdf=123";
var result = Regex.Replace(yourString, pattern, "asdf=bbbcccddd");

1 Comment

For such approach regex is overkill, just string.Replace will be enough msdn.microsoft.com/en-us/library/fk49wtc1(v=vs.110).aspx
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")

3 Comments

I do not need to reverse.. any string could be in there
@devhedgehog: I've updated my answer. Even though your edit changes your question completely.
The .*? part scares me in a large and arbitrary string of words. (\S*=) might be better.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.