繁体   English   中英

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

[英]Regex is not matching all alternate groups

输入字符串为:

<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

所使用的备用模式按其提供的顺序进行,也许这就是为什么它只吐出一组的原因,这是最后一个匹配项。

用正则表达式解析HTML数据不是一个好主意。 使用HtmlAgilityPack或用于此目的的类似库。 请参阅如何在vb.net中解析HTML

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

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演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM