开发者

Simple string 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


Regular expressions is massive overkill for this (and it often is). A simple:

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

will suffice.


You do not need regex for this, you can simply replace the values with String.Replace.

But if you are curious 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>";
    });


var res = Regex.Replace(input, @"(\\b0)|(\\b)", 
    m => m.Groups[1].Success ? "</b>" : "<b>");


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜