2013-07-03 97 views
1

我想使用vba正則表達式在html代碼中查找圖像。在下面的圖像名稱示例中,我只能找到第二個圖像,而不是第一個圖像。VBA正則表達式

.Pattern = "<img\s*src=""([^""]*)""" 

<img width="100%" src="red_blue.jpg"> 
<img src="img7993xyz71.jpg"> 
+0

替換'\ S *'和'*' –

+1

@DavidStarkey我會用'。*?'爲ungreedy匹配。 – HamZa

+0

@HamZa是的,我假設1''每行和'.'未設置爲匹配換行符。 –

回答

1

說明

與使用.*?的問題是,如果img標籤沒有src屬性,那麼你可能會匹配更多文本,然後你有興趣,或者你可能會意外地發現隨後的非img標記的src屬性。

這個正則表達式會捕獲整個img標籤,並將取出src屬性值。如果img標籤沒有src屬性,那麼img標籤將被跳過。

正則表達式:<img\b(?=\s)(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\ssrc=('[^']*'|"[^"]*"|[^'"][^\s>]*))(?:[^>=]|='[^']*'|="[^"]*"|=[^'"\s]*)*"\s?>

enter image description here

示例文本

注所述第二線具有一定的困難邊緣情況

<img width="100%" src="red_blue.jpg"> 
<img onmouseover=' var src="NotRealImage.png" ; funImageSwap(src); '><form><input type="image" src="submit.gif"></form> 
<img src="img7993xyz71.jpg"> 

代碼

我意識到這個例子是vb.net而不是vba,我只是包括這個來表明該解決方案將與.net正則表達式引擎一起工作。

VB.NET Code Example: 
Imports System.Text.RegularExpressions 
Module Module1 
    Sub Main() 
    Dim sourcestring as String = "replace with your source string" 
    Dim re As Regex = New Regex("<img\b(?=\s) # capture the open tag 
(?=(?:[^>=]|='[^']*'|=""[^""]*""|=[^'""][^\s>]*)*?\ssrc=('[^']*'|""[^""]*""|[^'""][^\s>]*)) # get the href attribute 
(?:[^>=]|='[^']*'|=""[^""]*""|=[^'""\s]*)*""\s?> # get the entire tag 
",RegexOptions.IgnoreCase OR RegexOptions.IgnorePatternWhitespace OR RegexOptions.Multiline OR RegexOptions.Singleline) 
    Dim mc as MatchCollection = re.Matches(sourcestring) 
    Dim mIdx as Integer = 0 
    For each m as Match in mc 
     For groupIdx As Integer = 0 To m.Groups.Count - 1 
     Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames(groupIdx), m.Groups(groupIdx).Value) 
     Next 
     mIdx=mIdx+1 
    Next 
    End Sub 
End Module 

匹配

[0][0] = <img width="100%" src="red_blue.jpg"> 
[0][1] = "red_blue.jpg" 
[1][0] = <img src="img7993xyz71.jpg"> 
[1][1] = "img7993xyz71.jpg" 
+0

謝謝!你的回答非常有幫助,我會改變我的代碼並測試它。 – user1218122