VBA从RegEx.Execute获取唯一值

如何过滤RegEx.Execute()以仅包含唯一匹配?

目前我有这个:

 Set allMatches = RE.Execute(text) 

而且我知道我可以通过元素循环:

 For i = 0 To allMatches.Count - 1 Next 

答案是在你的问题。 虽然for each next更清洁,可能会更快。 然后添加到脚本字典。 密钥是唯一的,所以如果字典中已经存在错误。

 Set Dict = CreateObject("Scripting.Dictionary") On Error Resume Next For each line in AllMatches Dict.Add Line, "" If Err.Number <> 0 then err.clear Next For Each thing in Dict.Keys() Outp.writeline thing Next 

您可以在比赛周围使用捕捉组,并在负向预览中使用反向参照。

想象一下,我们想从123 456 789 123 456 789456789唯一的3位数组。 我们需要将[0-9]{3}放入一个捕获组([0-9]{3})([0-9]{3}) ,然后检查这个捕获组是否在该string中没有重复。 所以,我们只捕获最后一个重复组。

 ([0-9]{3})(?!.*?\1.*$) 

示例VBA代码:

 Sub REGEXP_TEST_UNIQUE() Dim strPattern As String Dim strInput As String Dim regEx As New RegExp Dim objMatches As MatchCollection strInput = "123 456 789 123 456 789" strPattern = "([0-9]{3})(?!.*?\1.*$)" With regEx .Global = True .Pattern = strPattern End With If regEx.test(strInput) Then Set objMatches = regEx.Execute(strInput) For i = 0 To objMatches.Count - 1 Range("A2").Value = Range("A2").Value + " + " + objMatches.Item(i) Next End If End Sub 

“A2”单元格值变为:

 123 + 456 + 789 

使用一个字典,但没有不必要的error handling

 Sub recut() allMatches = Array("apple", "bannana", "apple", "pear") Set objdict = CreateObject("Scripting.Dictionary") For Each objmatch In allMatches If Not objdict.exists(objmatch) Then objdict.Add objmatch, 1 Next End Sub