2010-10-14 15 views
0

我剛剛編碼了下面的正則表達式。我在網頁上有一個迷你的富文本編輯器(非常類似於我用來發布此問題的編輯器),我想使用雙星號來指示哪些單詞/短語應該包裝在強標記中。其目的是允許用戶添加預定義的HTML元素,而不必實際提交HTML。如何進一步優化此正則表達式?

這裏是它的單元測試:

<TestMethod()> Public Sub Regular_Expression_Replaces_Double_Asterix_With_Strong_Tags() 

    'Arrange 
    Dim originalString As String = "This the start of the text. **This should be wrapped with a strong tag**. But this part should **not**. ** Note: this part should be left alone since it isn't closed off." 
    Dim htmlFormattedString As String = "This the start of the text. <strong>This should be wrapped with a strong tag</strong>. But this part should <strong>not</strong>. ** Note: this part should be left alone since it isn't closed off." 

    'Act 
    originalString = ItemTemplate.FormatTemplateToHtml(originalString) 

    'Assert 
    Assert.AreEqual(htmlFormattedString, originalString) 

End Sub 

這裏是工作代碼:

Public Shared Function FormatTemplateToHtml(ByVal value As String) As String 

    Dim formattedValue As String = value 
    Dim pattern As String = "(\*{2})(.*?)(\*{2})" 
    Dim regExMatches As MatchCollection = Regex.Matches(value, pattern) 

    For Each regExMatch As Match In regExMatches 

     'This is the part I feel could be improved? 
     Dim replaceableTag As String = regExMatch.Groups(0).Value 
     Dim reformattedTag As String = String.Format("<strong>{0}</strong>", regExMatch.Groups(2).Value) 
     formattedValue = formattedValue.Replace(replaceableTag, reformattedTag) 

    Next 

    Return formattedValue 

End Function 

也許我過優化,但我想知道是否可以這樣提高效率?

注:我同時使用VB.Net和C#專業所以儘管這個例子是在VB.Net(作爲該項目,這是因爲,在使用VB.Net)C#的答案,歡迎

回答

3

爲什麼不使用Replace方法?

Dim outputText As String = 
    Regex.Replace(inputText, "\*{2}(.*?)\*{2}", "<strong>$1</strong>") 
+0

因爲您可以使用$語法替換特定組的事實已經逃脫了我!優秀。 – BradB 2010-10-14 14:27:05