Simple line replace question in C #

I need to replace all occurrences of \b with <b> and all occurrences of \b0 with </b> in the following example:

The quick \ b brown fox \ b0 jumps over the \ b lazy dog โ€‹โ€‹\ b0.
. Thanks
+4
source share
4 answers

Regular expressions for this huge excess (and this often happens). Plain:

 string replace = text.Replace(@"\b0", "</b>") .Replace(@"\b", "<b>"); 

will be sufficient.

+10
source

You do not need a regular expression for this; you can simply replace the String.Replace values.

But if you are interested to know how this could be done with regex (Regex.Replace) , here is an example:

 var pattern = @"\\b0?"; // matches \b or \b0 var result = Regex.Replace(@"The quick \b brown fox\b0 jumps over the \b lazy dog\b0.", pattern, (m) => { // If it is \b replace with <b> // else replace with </b> return m.Value == @"\b" ? "<b>" : "</b>"; }); 
0
source
 var res = Regex.Replace(input, @"(\\b0)|(\\b)", m => m.Groups[1].Success ? "</b>" : "<b>"); 
0
source

As a quick and dirty solution, I would do it in 2 runs: first replace "\ b0" with "</b>" and then replace "\ b" with "<b>" .

 using System; using System.Text.RegularExpressions; public class FadelMS { public static void Main() { string input = "The quick \b brown fox\b0 jumps over the \b lazy dog\b0."; string pattern = "\\b0"; string replacement = "</b>"; Regex rgx = new Regex(pattern); string temp = rgx.Replace(input, replacement); pattern = "\\b"; replacement = "<b>"; Regex rgx = new Regex(pattern); string result = rgx.Replace(temp, replacement); } } 
0
source

All Articles