Reg. exp: substring AND whole string

2019-09-08 01:27发布

I'm working in VBscript. I have this string:

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

I want to extract "file", the filename, "try", the folder, "default", the other folder, AND I want to get the whole string, from < ! -- to -- > .

This regular expression gets me three matches:

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

The try, default, and file pieces, with submatches in each for the individual segments. That's great, but no matter what I add to the above expression to try and get the entire string as well, e.g.

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

I go from three matches to just one, losing the try/file/default pieces. There might be more than one @@include, so I need the whole match plus the submatches so I make sure to replace the right tag with the right content.

I can't figure how to alter the expression, help!

1条回答
贪生不怕死
2楼-- · 2019-09-08 02:08
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
查看更多
登录 后发表回答