regex - 从 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
解决方案
您可以使用正则表达式:
<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>”
推荐阅读
- excel - 为什么我的代码将第二行作为标题而不是第一行
- python - pytest:在每次 looponfail 运行时写入时间戳
- c - 让 MSVC 接近 clang 的性能
- php - PHP合并子数组
- hive - Hive:使用分区在 hive 表中查找最新日期
- http - 浏览器如何处理 Cache-Control 标头中的 `no-cache="Set-Cookie"`
- php - 使用嵌套的 for/foreach 循环时文件意外结束
- javascript - 如何在 React 中使内联样式使用状态?
- json.net - 如何将十进制序列化为字符串?
- go - 使用 * 实例化 var 时,单例测试不起作用