正则表达式:子串和整个字符串

时间:2015-03-12 17:09:53

标签: regex vbscript

我在VBscript工作。我有这个字符串:

hello
<!-- @@include file="filename" try="folder1" default="folder2" -->
world

我想要提取&#34;文件&#34;,文件名,&#34;尝试&#34;,文件夹,&#34;默认&#34;,另一个文件夹,我希望得到整个字符串,来自&lt; ! - 到 - &gt;

这个正则表达式给我三个匹配:

(try|default|file)(="([^"]+)")

try,default和file pieces,每个段的子匹配。这很棒,但无论我在上面的表达式中添加什么来尝试获取整个字符串,例如。

(!-- @@include (try|default|file)(="([^"]+)") -->)

我从三场比赛变为一场,失去了try / file / default。可能有多个@@ include,所以我需要整个匹配和子匹配,所以我确保用正确的内容替换正确的标记。

我无法想象如何改变表达,帮助!

1 个答案:

答案 0 :(得分:0)

strSample = "<!-- @@include file=""filename"" try=""folder1"" default=""folder2"" -->" & vbCrLf & "<!-- @@include default=""default first"" file=""filename at the end"" -->"

' this regex will match @@include lines which have the exact parameters set
With CreateObject("VBScript.RegExp")
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = "<!-- @@include file=""(.*?)"" try=""(.*?)"" default=""(.*?)"" -->"
    Set objMatches = .Execute(strSample)
    For Each objMatch In objMatches
        MsgBox "whole string:" & vbCrLf & objMatch.Value & vbCrLf & "file: " & objMatch.SubMatches(0) & vbCrLf & "try: " & objMatch.SubMatches(1) & vbCrLf & "default: " & objMatch.SubMatches(2), , "exact"
    Next
End With

' these nested regexes will match @@include lines which have any of three parameters in arbitrary order within line
With CreateObject("VBScript.RegExp")
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = "<!-- @@include (?:(?:try|default|file)="".*?"" )*?-->"
    For Each objLineMatch In .Execute(strSample)
        MsgBox "whole string:" & vbCrLf & objLineMatch.Value, , "arbitrary"
        With CreateObject("VBScript.RegExp")
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = "(try|default|file)=""(.*?)"""
            For Each objPropMatch In .Execute(objLineMatch.Value)
                MsgBox "Name: " & objPropMatch.SubMatches(0) & vbCrLf & "Value: " & objPropMatch.SubMatches(1), , "arbitrary"
            Next
        End With
    Next
End With