Regular expressions in .net provides a very easy and convienet way to do search and replace strings using patterns. Here is an example of how this works.
Let's take this string"This is a good place to do a test. And today is a sunday. A sunny sunday is a great day. A dog has eaten a chicken."
We want to replace every word that comes before the letter 'a' with "xyz". In this case the string should become"This xyz a good place to xyz a test. And today xyz a xyz A sunny sunday xyz a great xyz A dog has xyz a chicken."
What we want to do is look for a pattern like this -
Then we want to replace (anyword) with xyz in every occurence in the string. Let's now translate this pattern to a .net regular expression.
So, the complete regular expression becomes \S+\s+a\s+
Now let's see the code
string strTemp = "This is a good place to do a test. And today is a sunday. A sunny sunday is a great day. A dog has eaten a chicken."; string strPattern = @"\S+\s+a\s+"; string strReplacement = "xyz a "; Regex rgx1 = new Regex(strPattern, RegexOptions.IgnoreCase); strTemp = rgx1.Replace(strTemp, strReplacement); Console.WriteLine(strTemp);
Here is the output:blog comments powered by Disqus