REGEX提取多个名称/值标记(vbscript)

时间:2017-07-19 20:52:04

标签: regex 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" @-->

我尝试了十几种不同的变体,但到目前为止我最成功的是获得第一个名字=&#34;值&#34;对,没有别的,或者我得到整页的价值。所以所需的匹配是

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

我到目前为止最接近的是

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

但它只返回最后一对,而不是全部。

1 个答案:

答案 0 :(得分:0)

在VBScript中提到的两步流程@sln的实现:

now = datetime.datetime.now()

# create a user
u = User.create(username="user1", password="bla", last_login=now)
# now `u` has your user, you can do: print u.username, u.password, u.last_login

# get an existing user from the db
u = User.get(User.username == "user1")
print u.username, u.password, u.last_login

sleep(1)
now = datetime.datetime.now()

# update an existing user
u = User.update(password="blabla", last_login=now).where(User.username == "user1")
u.execute()

输出:

Option Explicit

Dim rCmt : Set rCmt = New RegExp
rCmt.Global = True
rCmt.Pattern = "<!-- @[\s\S]+?@-->"
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

由于盖茨先生Doc for the .Replace方法很糟糕,请参阅123