正则表达式不匹配所有备用组

时间:2016-11-09 06:16:06

标签: .net regex vb.net

输入字符串是:

<input type="hidden" name="locale" value="us">

正则表达式模式是:

Dim r As New Regex("<input\s{0,}(?:(name|type|value)=""([^""]+)""\s{0,})+>")

正在使用的代码:

        If r.IsMatch(s) Then
            For Each m As Match In r.Matches(s)
                Debug.Print(m.ToString)
                For i As Integer = 0 To m.Groups.Count - 1
                    Debug.Print(New String(" "c, i + 1) & "-" & m.Groups(i).Value)
                Next
            Next
        End If

输出:

<input type="hidden" name="locale" value="us">
 -<input type="hidden" name="locale" value="us">
  -value
   -us

我希望它匹配:

-type
-hidden
-name
-locale
-value
-us

使用的替代模式按其提供的顺序排列,也许这就是为什么它只吐出一个组,这是最后一个匹配。

1 个答案:

答案 0 :(得分:0)

用正则表达式解析HTML数据不是一个好主意。使用HtmlAgilityPack或类似的库来执行此操作。请参阅How do you parse an HTML in vb.net

回答您的问题,您不会访问存储在每个组的捕获集合中的捕获。这是一个简单的代码段,展示了如何使用相同的正则表达式获得所需的结果:

Imports System
Imports System.Text.RegularExpressions

Public Class Test
    Public Shared Sub Main()
        Dim r As New Regex("<input\s{0,}(?:(name|type|value)=""([^""]+)""\s{0,})+>")
        Dim s As String
        s = "<input type=""hidden"" name=""locale"" value=""us"">"
        If r.IsMatch(s) Then
            For Each m As Match In r.Matches(s)
                Console.WriteLine(m.ToString)
                For j As Integer = 0 To m.Groups(1).Captures.Count - 1      ' Number of captures in Capture stack 1 (same will be in the second one)
                    Console.WriteLine(" -" & m.Groups(1).Captures(j).Value) ' Print the 1st group captures
                    Console.WriteLine(" -" & m.Groups(2).Captures(j).Value) ' Print the 2nd group captures
                Next
            Next
        End If
    End Sub
End Class

输出:

<input type="hidden" name="locale" value="us">
 -type
 -hidden
 -name
 -locale
 -value
 -us

请参阅VB.NET demo