Excle使用正则提取字符串

发布时间 2023-07-06 17:33:13作者: 过氧化氢

1、Alt+F11打开VB编辑工具

2、选择sheet创建新模块

3、插入下列代码

Function RegexExtract(ByVal inputString As String) As String
    Dim regEx As Object
    Set regEx = CreateObject("VBScript.RegExp")
    
    With regEx
        .Global = True
        .Pattern = "\((\w{1,3})\)" ' 此处正则表达式可根据你的具体需求进行修改
    End With
    
    If regEx.test(inputString) Then
        Set matches = regEx.Execute(inputString)
        RegexExtract = matches(0).SubMatches(0)
    Else
        RegexExtract = ""
    End If
End Function

4、保存为宏工作簿

 5、在该sheet表格中调用即可