2012-04-04 72 views
5

我想知道是否有任何方法可以替換字符串中的子字符串,但替換它們之間的替換字符串。 I.E,匹配字符串"**"的所有出現,並用"<strong>"代替第一次出現,然後用"</strong>"代替第一次出現(然後重複該模式)。交替替換子串

的投入將是這樣的:"This is a sentence with **multiple** strong tags which will be **strong** upon output"

而返回的輸出將是:"This is a sentence with <strong>multiple</strong> strong tags which will be <strong>strong</strong> upon output"

+2

您可以在循環中將'IndexOf'與開始索引一起使用。 – CodesInChaos 2012-04-04 10:49:50

+0

@CodeInChaos我沒有真正使用IndexOf,經常會看看它,但你會有任何實現方法? – JakeJ 2012-04-04 10:51:18

回答

6

您可以使用Regex.Replace,需要一個MatchEvaluator委託過載:

using System.Text.RegularExpressions; 

class Program { 
    static void Main(string[] args) { 
     string toReplace = "This is a sentence with **multiple** strong tags which will be **strong** upon output"; 
     int index = 0; 
     string replaced = Regex.Replace(toReplace, @"\*\*", (m) => { 
      index++; 
      if (index % 2 == 1) { 
       return "<strong>"; 
      } else { 
       return "</strong>"; 
      } 
     }); 
    } 
} 
+0

現貨。 +1。 – SkonJeet 2012-04-04 10:53:27

+0

@Paolo我只是再次使用它,並意識到如果用'return index%2 == 1替換'if'語句,代碼可以縮短並看起來好一點? 「」:「」;' – JakeJ 2012-05-01 10:10:51

1

的最簡單的方法是實際應用**(content)**而不是**。然後你用<strong>(content)</strong>代替,就完成了。

您可能還想查看MarkdownSharp的https://code.google.com/p/markdownsharp,因爲這實際上是您似乎想要使用的。

+0

這是最乾淨的方法,+1。 – 2012-04-04 10:55:33

+0

我看過MarkDownSharp,但我只想輸入粗體,而不是整個特徵。我可能會開始使用它,當它被要求更頻繁 – JakeJ 2012-04-04 10:59:26

-1

試試吧

var sourceString = "This is a sentence with **multiple** strong tags which will be **strong** upon output"; 
var resultString = sourceString.Replace(" **","<strong>"); 
resultString = sourceString.Replace("** ","</strong>"); 

歡呼聲,

+0

,顯然不符合他的規範。 – CodesInChaos 2012-04-04 10:54:27

+0

如果空間不存在,這會搞砸,而且沒有理由他們應該這樣做。 – 2012-04-04 10:55:55

+1

這適用於我指定的輸入,但如果'**'的起始組位於字符串的起始位置,則存在問題 – JakeJ 2012-04-04 10:57:52

-3

我認爲你應該使用正則表達式匹配的模式,並取代它,它很容易。

+0

答案太簡單了。請提供尚未提供的代碼示例。 – vapcguy 2016-10-27 18:45:59

1

您可以使用正則表達式來解決這個問題:

string sentence = "This is a sentence with **multiple** strong tags which will be **strong** upon output"; 

var expression = new Regex(@"(\*\*([a-z]+)\*\*)"); 

string result = expression.Replace(sentence, (m) => string.Concat("<strong>", m.Groups[2].Value, "</strong>")); 

這種方法會自動處理語法錯誤(想想一個字符串像This **word should be **strong**)。