我正在编写一个 excel 宏,以便能够搜索一个 excel 列表,并且除其他外,将匹配项(如果有)写入不同的单元格。
我从 this 那里得到了很多帮助很好的解释,但我不知道如何只将正则表达式匹配写入单元格。我当前的代码在匹配后剪切字符串并将其写入单元格。但我只想写匹配,而不是字符串中的其他内容。
这是我的代码:
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 列中的红色文本是初始字符串的完全匹配,B 和 D 列中的红色是分隔的匹配项。所以这几乎是我想要的,但我只想在单元格 B-D 中匹配,而不是整个字符串。
对不起,示例中的瑞典语,我的数据集来自瑞典网站。但我认为你还是有问题吗?
最佳答案
您需要使用 .regEx.Execute(str)
并访问 SubMatches
值(value)观:
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)
表示获取第一个匹配项,第一个捕获组值。
关于regex - 将几个正则表达式匹配写入excel中的不同单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42558687/