正则expression式在VBA – 如何恢复search?
祝大家好日子。
我有一个问题与VBA及其正则expression式的实现。
在Javascript中,当我多次使用Execute方法时,引擎会在停止的地方恢复。
下面的例子:
<script> var subject = '?{testtag}?+{4065}?{testtag}?'; var regex = /\?[^\?]+\?|({[^}]+})/g; var match for (var i = 0; i < 10; i++) { match = regex.exec(subject) console.log(match) } </script>
返回
["?{testtag}?", undefined, index: 0, input: "?{testtag}?+{4065}?{testtag}?"] ["{4065}", "{4065}", index: 12, input: "?{testtag}?+{4065}?{testtag}?"] ["?{testtag}?", undefined, index: 18, input: "?{testtag}?+{4065}?{testtag}?"] null ["?{testtag}?", undefined, index: 0, input: "?{testtag}?+{4065}?{testtag}?"] ["{4065}", "{4065}", index: 12, input: "?{testtag}?+{4065}?{testtag}?"] ["?{testtag}?", undefined, index: 18, input: "?{testtag}?+{4065}?{testtag}?"] null ["?{testtag}?", undefined, index: 0, input: "?{testtag}?+{4065}?{testtag}?"] ["{4065}", "{4065}", index: 12, input: "?{testtag}?+{4065}?{testtag}?"]
正如你所看到的,发动机在比赛结束后恢复。
在VBA中同样的事情:
Sub test_regex() Dim regEx As New RegExp Dim matches As Object Dim source_string As String source_string = "?{testtag}?+{4065}+?{testtag}?" With regEx .pattern = "\?[^\?]+\?|({[^}]+})" End With For i = 1 To 10 Set matches = regEx.Execute(source_string) Debug.Print (matches(0)) Next End Sub
返回
?{testtag}? ?{testtag}? ?{testtag}? ?{testtag}? ?{testtag}? ?{testtag}? ?{testtag}? ?{testtag}? ?{testtag}? ?{testtag}?
第0个元素是数组中唯一的元素。 在每次调用时,引擎似乎都会在string的开始处重新开始。
有没有办法让VBA像JS一样行事?
非常感谢你的帮助,
首先,VBScript的RegExp对象要求你明确地设置一个布尔值的Global
标志,并且.Execute()
方法返回一组匹配,你只需要遍历每一个:
Sub MM_Demo() Dim regEx As New RegExp Dim matches As MatchCollection Dim source_string As String source_string = "?{testtag}?+{4065}+?{testtag}?" With regEx .Pattern = "\?[^\?]+\?|({[^}]+})" .Global = True '// <~~ global flag End With Set matches = regEx.Execute(source_string) '// I'm going for a For Each loop, but it's down to preference For Each Match In matches Debug.Print CStr(Match) Next End Sub
这将输出:
?{testtag}? {4065} ?{testtag}?
还有一个.SubMatches
集合,你可以通过这种方式设置你的模式。 例如:
For Each subMatch In matches(0).SubMatches Debug.Print CStr(subMatch) Next
- 使用macros从Microsoft Outlook Messsage中提取所有IP地址
- VBA中的RegEx:将复杂的string分解为多个标记?
- 用excel.interopreplaceexcel中的单元格值
- 如何在Excel中使用正则expression式来查找/replacestring的结尾
- 使用正则expression式创build分隔文本
- VBA正则expression式 – 试图replacestring中的字符时运行时错误91
- 如何构build正则expression式来查找单元格中的“”的不常见
- 如何在Excel中使用Excelreplace<*>如在Excel中? (常用expression)
- 在Excel或R中匹配通配符数组