簡體   English   中英

有沒有辦法正則表達式多行 html 塊?

[英]is there a way to regex multiline html blocks?

它是我的 html 頁面的一部分。 我想找到標記之間的所有名稱: <a href ... </a></td> 它的多行和“新”關鍵字每次都有不同的數字。

        <tr class="hl">
        <td class="vil fc">
            <a href="mypage.php?new=4645">
                name                </a>
        </td>

默認情況下, Regex類會搜索整個多行字符串,並且會查找跨越多行的匹配項。 但是,匹配項是否可以跨越多行取決於您的模式。 如果你給它的模式說匹配必須全部在一行上,那么它顯然不會返回任何多行匹配。 因此,例如:

Dim input As String = "Canine
Dog
K9
D
o
g
Puppy"
Dim count As Integer = Regex.Matches(input, "Dog").Count 
Dim countMulti As Integer = Regex.Matches(input, "D\s*o\s*g").Count 
Console.WriteLine(count)      ' Outputs "1"
Console.WriteLine(countMulti) ' Outputs "2"

由於\\s*表示任意數量的空格(包括換行符),因此第二個模式將匹配第二個模式,其中每個字母都在自己的行上。

因此,如果它默認有效,並且您正在詢問它,我認為真正的問題是您不允許在模式中使用換行符。 因此,例如,這將起作用:

Dim input As String = "<tr class=""hl"">
<td class=""vil fc"">
<a href=""mypage.php?New=4645"">
        name                </a>
</td>"
Dim m As Match = Regex.Match(input, "<a[^>]*>((?:.|\s)*?)</a>")
If m.Success Then
    Dim g As String = m.Groups(1).Value
    Console.WriteLine(g)  ' Outputs vbCrLf & "                name                "
End If

一個常見的假設是. 將匹配任何內容,包括換行符,但通常情況並非如此。 默認情況下, . 只有匹配任何不是新行字符。 如果你想要. 要還包括換行符,您可以通過指定可能會引起混淆的RegexOptions.Singleline選項來實現。 例如,這也有效:

Dim input As String = "<tr class=""hl"">
<td class=""vil fc"">
<a href=""mypage.php?New=4645"">
        name                </a>
</td>"
Dim m As Match = Regex.Match(input, "<a[^>]*>(.*?)</a>", RegexOptions.Singleline)
If m.Success Then
    Dim g As String = m.Groups(1).Value
    Console.WriteLine(g)  ' Outputs vbCrLf & "                name                "
End If

或者,您可以在正則表達式模式本身中指定單行選項,方法是將(?s)放在開頭:

Dim m As Match = Regex.Match(input, "(?s)<a[^>]*>(.*?)</a>")

為了解決您在評論中提到的其他問題,如果您只想匹配包含newdid參數的鏈接,您可以執行以下操作:

<a\s+[^>]*href\s*=[^>]*newdid\s*=[^>]*>(.*?)</a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM