2011-07-05 33 views
4

我需要</b>以取代<b>\b所有出现和\b0所有出现在下面的例子: 简单的字符串替换的问题在C#

快速\ b的棕色狐狸\ B0跃过\ b懒狗\ B0 。
。谢谢

+1

是什么问题?你在寻找一个正则表达式生成器吗? – 2011-07-05 17:05:06

+0

是的。 Reqex表达。 – FadelMS

+0

Steve,我遇到了一个问题,并试图用不同的方法来解决它。到目前为止没有运气。 – FadelMS

回答

10

正则表达式是这个(通常是)大规模矫枉过正。一个简单的:

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

就足够了。

+1

谢谢杰森,解决了。 – FadelMS

0

你并不需要为这个正则表达式,你可以简单地replace the values with String.Replace.

但是,如果你想知道这到底是怎么done with regex (Regex.Replace)这里有一个例子:

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

作为一个快速和肮脏的解决方案,我会做2次运行:首先用"</b>"替换“\ b0”,然后用"<b>"替换“\ 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); 

    } 
}