写几个正则expression式匹配不同的单元格在Excel中

我正在写一个Excelmacros,可以search一个Excel列表,除其他外,将匹配(如果有的话)写入不同的单元格。

我从这个很好的解释中得到了很多帮助,但是我不能弄清楚的是如何只给单元格写正则expression式匹配。 我当前的代码在匹配后剪切string并将其写入单元格。 但是我只想写下比赛,没有其他的string。

这是我的代码:

Private Sub simpleRegex() Dim strPattern As String Dim strReplace As String Dim regEx As New RegExp Dim strInput As String Dim Myrange As Range Set Myrange = ActiveSheet.Range("A1:A5") For Each cell In Myrange strPattern = "(storlek|strl|stl|strlk|storleken|storl|size|storleksmärkt|storl|storlk|st)(.{0,2}?)((30|32|34|36|38|40|42|44|46|48|50))(.?)((30|32|34|36|38|40|42|44|46|48|50)?)" If strPattern <> "" Then strInput = cell.Value strReplace = "$1" With regEx .Global = True .MultiLine = True .IgnoreCase = False .Pattern = strPattern End With If regEx.test(strInput) Then cell(1, 5).Value = 1 cell(1, 2).Value = regEx.Replace(strInput, "$1") cell(1, 3).Value = regEx.Replace(strInput, "$2") cell(1, 4).Value = regEx.Replace(strInput, "$3") Else cell(1, 6).Value = 1 End If End If Next End Sub 

这是我在Excel中得到的结果:

在这里输入图像说明

因此,A列中的红色文本是与初始string完全匹配的,而B列和D列中的红色是分隔的匹配。 所以它几乎是我想要的,但我只想在单元格BD中的匹配不是整个string。

对不起,瑞典在这个例子中,我的数据集来自瑞典的网站。 但是我认为你会遇到问题吗?

您需要使用.regEx.Execute(str)并访问SubMatches值:

 Dim objMatchs As MatchCollection ' ... Set objMatches = regEx.Execute(strInput) If objMatches.Count <> 0 Then cell(1, 5).Value = 1 cell(1, 2).Value = objMatches(0).SubMatches(0) cell(1, 3).Value = objMatches(0).SubMatches(1) cell(1, 4).Value = objMatches(0).SubMatches(2) End If 

捕获组ID以从0开始的索引开始。

objMatches(0).SubMatches(0)表示获得第一个匹配,即第一个捕获组的值