首页 > 解决方案 > 从 VB.Net 中 Span 元素之间的字符串中删除文本

问题描述

我有看起来像这样的字符串:

%20-%20<span%20style=color:Red;>Pepsi%20Max</span>%20+%20£3%20Tip

我希望删除所有存在的:

<span%20style=color:Red;>ANY TEXT</span> 

完全来自字符串。所以为了澄清,字符串可能包含多个文本跨度,其中颜色设置为红色,我希望删除这些文本,所以在这种情况下,字符串看起来像这样:

%20-%20%20+%20£3%20Tip

我需要在 VB.Net 中执行此操作,并且真的不知道从哪里开始。任何帮助表示赞赏。

Dim orderSentence As String = Label1.Text

Dim shortenedOrderSentence As New Regex("<span%20style=color:Red;>.*<\/span>")
Dim str as string = shortenedOrderSentence.Replace(orderSentence, "")
Label1.text = str

标签: regexvb.net

解决方案


您可以使用正则表达式:

<span%20style=Red;>.*<\/span>

并用空字符串替换它,你会得到你想要的。因此,使用 Regex 类和您的示例:

Dim r As New Regex("<span%20style=Red;>.*<\/span>")
Dim str as string = r.Replace("%20-%20<span%20style=Red;>Pepsi%20Max</span>%20+%20£3%20Tip", "")

字符串变量将包含预期的字符串。

编辑:在测试页面中使用

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim orderSentence As String = "%20-%20<span%20style=color:Red;>Pepsi%20Max</span>%20+%20£3%20Tip"

    Context.Response.Write("Original string: ")
    Context.Response.Write(orderSentence)

    Context.Response.Write("<br /><br />")

    Dim shortenedOrderSentence As New Regex("<span%20style=color:Red;>.*<\/span>")

    Context.Response.Write("Result string: ")
    Context.Response.Write(shortenedOrderSentence.Replace(orderSentence, ""))
End Sub

浏览器中的结果:

在此处输入图像描述

对于解码的字符串(%20 是白色字符),使用另一个正则表达式,例如“<span\sstyle=color:Red;>.*</span>”


推荐阅读