如何捕获 <TAGs> 内的文本,但是通过从结果中排除标签?

How to capture text inside <TAGs> , BUT by excluding the tags from result?

在 Visual Basic 中,我试图在标签之间获取文本,但 TAGS 也被捕获。

Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim pattern As String = "<tag>(.+?)<\/tag>"
    Dim text As String = "Other Text <tag>Captured Text</tag> Other Text"
    Dim capture As Match = Regex.Match(text, pattern)
    MsgBox(capture.Value)
End Sub

我想在消息框中仅 "Captured Text" 看到结果。

但结果是“...Captured Text...”,前后都有标签。

我的代码有什么问题?

您应该访问第 1 组值:

MsgBox(capture.Groups(1).Value)

您使用的模式包含一个用一对非转义括号定义的捕获组,该部分使正则表达式引擎将捕获的值存储在某个内存缓冲区中。这样的内存缓冲区的数量与捕获组的数量一样多,加上一个索引为 0 的组,该组包含整个匹配值。您需要访问第 1 组值。

另请注意,capture 变量名称在这里具有误导性,因为捕获是存储在组堆栈中的值,而 Regex.Match returns 包含所有组的 Match 对象并捕获值和有关它们的一些信息。