FadelMS
FadelMS

Reputation: 2037

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

Upvotes: 4

Views: 1049

Answers (4)

bvgheluwe
bvgheluwe

Reputation: 853

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);

   }
}

Upvotes: 0

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56222

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

Upvotes: 0

BrunoLM
BrunoLM

Reputation: 100381

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>";
    });

Upvotes: 0

jason
jason

Reputation: 241779

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

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

will suffice.

Upvotes: 10

Related Questions