VBA正则表达式

问题描述 投票:1回答:1

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

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

<img width="100%" src="red_blue.jpg">
<img src="img7993xyz71.jpg">
regex vba ms-word word-vba
1个回答
1
投票

Description

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

这个正则表达式将捕获整个img标记,并将拉出src属性值。如果img标记没有src属性,则将跳过img标记。

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

Example

示范文本

注意第二行有一些困难的边缘情况

<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"
© www.soinside.com 2019 - 2024. All rights reserved.