VBScript - RegEx - 修改ObjMatch - Pattern =“(\ d {2})(\ d {2})(\ d {2})”

时间:2014-02-06 07:11:40

标签: regex vbscript

这是我在尝试学习一些关于Reg Ex的事情时偶然发现的事情。

Set objRegEx = CreateObject("VBScript.RegExp")
Dim re, targetString, colMatch, objMatch
Set re = New RegExp
With re
.Pattern = "(\d{2}) (\d{2}) (\d{2}) 0500Z"
.Global = True
.IgnoreCase = True
End With 
targetString = "02 04 14 0500Z Joe is eating a sandwich"

Set colMatch = re.Execute(targetString)
For each objMatch  in colMatch
WScript.echo objMatch

date1 = objRegEx.Replace(objMatch, "(\d{2})(\d{2})(\d{2})")
Wscript.Echo date1

问题:我需要找到显示的日期,如“02 04 14 0500Z”,然后将其分配给“020414”形式的变量。

当我尝试替换Obj匹配并重新格式化日期时它不起作用,而是在括号中显示确切的文本。

我引用了: http://www.mikesdotnetting.com/Article/24/Regular-Expressions-and-VBScript http://wiki.mcneel.com/developer/scriptsamples/regexpobject

1 个答案:

答案 0 :(得分:1)

要引用捕获组捕获的内容,请在替换字符串中使用$n(其中n是数字):

date1 = re.Replace(objMatch, "$1$2$3")

要识别捕获组的编号,请计算属于捕获组的开放括号(的数量,直至您要引用的捕获组:

(\d{2}) (\d{2}) (\d{2}) 0500Z
^       ^       ^
1       2       3

一个更复杂的例子:

((a(?:k)*)(b(c)(?:d)*))
^^        ^ ^
12        3 4

(?:pattern)是一个非捕获组,因此不计算在内。