我刚刚编写了下面的正则表达式。我在网页上有一个迷你富文本编辑器(非常类似于我用来发布这个问题的编辑器),我想使用双星号来指示哪些单词/短语应该包含在强标签中。目的是允许用户添加预定义的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#answers欢迎。
答案 0 :(得分:3)
为什么不使用Replace
方法?
Dim outputText As String =
Regex.Replace(inputText, "\*{2}(.*?)\*{2}", "<strong>$1</strong>")