【问题标题】:Regex is not matching all alternate groups正则表达式不匹配所有备用组
【发布时间】:2016-11-09 06:16:05
【问题描述】:

输入字符串为:

<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是如此复杂,以至于正确的正则表达式会巨大 .
  • 我只想匹配这个字符串,而不是整个 HTML 页面。为了帮助您的观点,我知道这可以很容易地使用 .IndexOf 和 .Substring 等解析出来。
  • 是的。然后它将引号更改为'。或者在= 周围添加一些空格。或者出现一个无价值的属性。你知道我要去哪里吗?

标签: .net regex vb.net


【解决方案1】:

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

回答您的问题,您不会访问所有存储在每个组的捕获集合中的捕获。这是一个简单的 sn-p,展示了如何使用 相同的 regex 获得所需的结果:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    相关资源
    最近更新 更多