[英]How can I further optimise this regular expression?
我剛剛編寫了以下正則表達式。 我在網頁上有一個微型富文本編輯器(非常類似於我用來發布此問題的文本編輯器),並且我想利用雙星號來指示應將哪些單詞/短語包裹在強標簽中。 目的是允許用戶添加預定義的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#答案 。
您為什么不只使用Replace
方法?
Dim outputText As String =
Regex.Replace(inputText, "\*{2}(.*?)\*{2}", "<strong>$1</strong>")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.