2011-07-05 34 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); 

    } 
}