4

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

2
  • 1
    what is the question ? are you looking for a regex builder ? Commented Jul 5, 2011 at 17:05
  • Steve, I'm stuck with a problem and trying different ways to solve it. No luck so far. Commented Jul 5, 2011 at 17:08

4 Answers 4

10

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

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

will suffice.

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

Comments

0

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

Comments

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

Comments

0

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

   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.