如何在VB.NET中使用正则表达式提取指定符号之间的文本
VB.NET 正则提取实现方案
首先引入必备命名空间:
Imports System.Text.RegularExpressions
1. 提取等号之间的标题
匹配逻辑:匹配连续等号包裹的文本,自动过滤前后的等号和多余空白。
正则模式:=+(.*?)=+
实现代码:
' 待处理的原始文本 Dim rawContent As String = "===%Summary%=== Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. ### Trip:No/Yes | Billed:Yes/No ###" ' 匹配标题 Dim titleMatch As Match = Regex.Match(rawContent, "=+(.*?)=+") If titleMatch.Success Then ' 提取结果为 %Summary% Dim title = titleMatch.Groups(1).Value.Trim() Console.WriteLine(title) End If
2. 提取#符号之间的Trip和Billed相关文本
匹配逻辑:匹配连续#包裹、且包含Trip/Billed关键词的文本,支持忽略大小写匹配。
正则模式:#+(.*?(Trip|Billed).*?)#+
实现代码:
' 匹配Trip/Billed信息 Dim tripMatch As Match = Regex.Match(rawContent, "#+(.*?(Trip|Billed).*?)#+", RegexOptions.IgnoreCase) If tripMatch.Success Then ' 提取结果为 Trip:No/Yes | Billed:Yes/No Dim tripInfo = tripMatch.Groups(1).Value.Trim() Console.WriteLine(tripInfo) End If
正则参数说明
+:匹配1个及以上的连续对应符号,兼容标记数量不固定的场景.*?:非贪婪匹配,尽可能缩短匹配范围,避免多个同类标记出现时匹配内容过长RegexOptions.IgnoreCase:忽略大小写匹配,兼容小写的trip、billed场景
内容的提问来源于stack exchange,提问作者user16483558
相关产品推荐
相关产品推荐

