VBA正则表达式

时间:2013-07-03 15:40:45

标签: regex vba ms-word word-vba

我正在尝试使用vba正则表达式来查找html代码中的图像。在下面的图像名称示例中,我只找到第二张图像而不是第一张图像。

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

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

1 个答案:

答案 0 :(得分:1)

描述

使用.*?的问题是,如果img标签没有src属性,那么您可能会匹配更多文本然后您感兴趣,或者您可能会意外地找到后续的src属性非img标签。

这个正则表达式将捕获整个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"