excel中使用正则表达式提取单元格中匹配的字符
来源:网络收集 点击: 时间:2025-05-16新建一个EXCEL表格

按ALT+F11打开VBA的代码窗口

鼠标右键点击项目,选择“插入”-“模块”

在新出的窗口中输入以下代码:
Function RegexMatch(cellValue As String, pattern As String)
Dim regex As Object
Dim matches As Object
Dim match As Object
Dim result As String
Set regex = CreateObject(VBScript.RegExp)
regex.Global = True
regex.Pattern = pattern
If regex.test(cellValue) Then
Set matches = regex.Execute(cellValue)
For Each match In matches
result = result match.Value
Next match
RegexMatch = Trim(result)
Else
RegexMatch = No match found
End If
End Function

并将文件保存为 excel启用宏的工作薄

最后可以在单元格中输入=RegexMatch(A3,\d+),可以获取对应的内容

如果有匹配项,则函数将返回一个字符串,其中包含所有的匹配项,以空格分隔。如果没有匹配项,则返回No match found。
正则表达式可以替换成自己需求的表达式
版权声明:
1、本文系转载,版权归原作者所有,旨在传递信息,不代表看本站的观点和立场。
2、本站仅提供信息发布平台,不承担相关法律责任。
3、若侵犯您的版权或隐私,请联系本站管理员删除。
4、文章链接:http://www.1haoku.cn/art_1250529.html