2017-07-19 33 views
0

給定一個模板,看起來像這樣:正則表達式來提取多個名稱/值令牌(VBScript)的

<td class="creditapp heading">{*}Street Address:</td> 
<td colspan=2 class="tdaddressblock"> 
<!-- @template="addressBlock" for="buyer" prev="" @--> 
    ^^ might be a space here, might not  ^^ always a space here 
</td> 

我需要閱讀name = value對出來​​的評論,加上整個字符串,因此可以被替換。名稱可以是任何字母數字,不帶空格,值可以包含除雙引號以外的任何內容,儘可能短,並且總是用雙引號括起來。

所以,可能的格式:

<!-- @pizza="yes" @--> 
<!-- @ingredients="cheese sauce meat" @--> 
<!-- @ drinks="yes, please" breadsticks="garlic, butter (lots); cheese" @--> 

我已經嘗試了十幾種不同的變化,但最成功的我一直到目前爲止是獲得頭名=「值」對,沒有別的,或者我得到整個頁面值得的東西。因此,所需的匹配是

[1] <!-- @ drinks="yes, please" breadsticks="garlic, butter (lots); cheese" @--> 
[2] drinks 
[3] yes, please 
[4] breadsticks 
[5] garlic, butter (lots); cheese 

到目前爲止我來最接近的是

<!-- @((|)([\w]+)="(.*?)")+ @--> 

但它只返回最後一對,不是所有的人。

+0

你不能這樣做。這是一個兩步過程。在替換回調中,匹配整個評論''。每場比賽抓取內容,對內容進行另一次正則表達式。 '\ b(\ w +)\ s * = \ s *「([^」] *)「',進行任何操作,然後將內容寫回原來的替換內容。如果不是,你需要在while循環中自己構造新的字符串 – sln

+0

請注意,如果你沒有替換,使用Dot-Net正則表達式,你可以使用_Capture Collection_來獲得一切匹配。例如:<! - (?:。*?\ b(\ w +)\ s * = \ s *「([^」] *)「)*。*? - >'分別是組1和組2數組[索引](分別)。 – sln

回答

0

2種方法的實施@sln在VBScript提到:

Option Explicit 

Dim rCmt : Set rCmt = New RegExp 
rCmt.Global = True 
rCmt.Pattern = "<!-- @[\s\S][email protected]>" 
Dim rKVP : Set rKVP = New RegExp 
rKVP.Global = True 
rKVP.Pattern = "(\w+)=""([^""]*)""" 
Dim sInp : sInp = Join(Array(_ 
    "<td class=""creditapp heading"">{*}Street Address:</td>" _ 
    , "<td colspan=2 class=""tdaddressblock"">" _ 
    , "<!-- @template=""addressBlock"" for=""buyer"" prev="""" @-->" _ 
, "</td>" _ 
, "<!-- @ pipapo=""i dont care""" _ 
, "rof=""abracadabra"" prev="""" @-->" _ 
), vbCrLf) 

WScript.Echo sInp 
WScript.Echo "-----------------" 
WScript.Echo rCmt.Replace(sInp, GetRef("fnRepl")) 
WScript.Quit 0 

Function fnRepl(sMatch, nPos, sSrc) 
    Dim d : Set d = CreateObject("Scripting.Dictionary") 
    Dim ms : Set ms = rKVP.Execute(sMatch) 
    Dim m 
    For Each m In ms 
     d(m.SubMatches(0)) = m.SubMatches(1) 
    Next 
    fnRepl = "a comment containing " & Join(d.Keys) 
End Function 

輸出:

cscript 45200777-2.vbs 
<td class="creditapp heading">{*}Street Address:</td> 
<td colspan=2 class="tdaddressblock"> 
<!-- @template="addressBlock" for="buyer" prev="" @--> 
</td> 
<!-- @ pipapo="i dont care" 
rof="abracadabra" prev="" @--> 
----------------- 
<td class="creditapp heading">{*}Street Address:</td> 
<td colspan=2 class="tdaddressblock"> 
a comment containing template for prev 
</td> 
a comment containing pipapo rof prev 

作爲蓋茨Doc for the .Replace方法吮吸,見123