regex - 如何在单元格内和循环中使用 Microsoft Excel 中的正则表达式 (Regex)

标签 regex excel vba

如何在 Excel 中使用正则表达式并利用 Excel 强大的类似网格的设置进行数据操作?

  • 在单元格函数中返回匹配的模式或字符串中的替换值。
  • Sub 循环遍历一列数据并提取与相邻单元格的匹配项。
  • 需要什么设置?
  • Excel 的正则表达式特殊字符是什么?


  • 我知道 Regex 在许多情况下并不理想( To use or not to use regular expressions? ),因为 excel 可以使用 Left , Mid , Right , Instr键入用于类似操作的命令。

    最佳答案

    Regular expressions用于模式匹配。
    要在 Excel 中使用,请按照下列步骤操作:
    步骤 1 : 添加对“Microsoft VBScript 正则表达式 5.5”的 VBA 引用

  • 选择“开发人员”选项卡 ( I don't have this tab what do I do? )
  • 从“代码”功能区部分选择“Visual Basic”图标
  • 在“Microsoft Visual Basic for Applications”窗口中,从顶部菜单中选择“工具”。
  • 选择“引用”
  • 选中“Microsoft VBScript 正则表达式 5.5”旁边的框以包含在您的工作簿中。
  • 点击“确定”

  • 步骤 2 :定义你的模式
    基本定义:-范围。
  • 例如。 a-z匹配从 a 到 z 的小写字母
  • 例如。 0-5匹配从 0 到 5 的任何数字
  • []完全匹配这些括号内的对象之一。
  • 例如。 [a]匹配字母 a
  • 例如。 [abc]匹配单个字母,可以是 a、b 或 c
  • 例如。 [a-z]匹配字母表中的任何单个小写字母。
  • ()将不同的匹配分组以用于返回目的。请参阅下面的示例。{}之前定义的模式重复副本的乘数。
  • 例如。 [a]{2}匹配两个连续的小写字母 a:aa
  • 例如。 [a]{1,3}匹配至少一个和最多三个小写字母 a , aa , aaa
  • +匹配至少一个或多个在它之前定义的模式。
  • 例如。 a+将匹配连续的 a a , aa , aaa ,等等
  • ?匹配零个或在它之前定义的模式之一。
  • 例如。模式可能存在也可能不存在,但只能匹配一次。
  • 例如。 [a-z]?匹配空字符串或任何单个小写字母。
  • *匹配零个或多个在它之前定义的模式。
  • 例如。可能存在也可能不存在的模式的通配符。
  • 例如。 [a-z]*匹配空字符串或小写字母字符串。
  • .匹配除换行符之外的任何字符 \n
  • 例如。 a.匹配以 a 开头并以除 \n 以外的任何内容结尾的两个字符串
  • |或运算符
  • 例如。 a|b表示 ab可以匹配。
  • 例如。 red|white|orange与其中一种颜色完全匹配。
  • ^非运算符
  • 例如。 [^0-9]字符不能包含数字
  • 例如。 [^aA]字符不能为小写 a或大写 A
  • \转义后面的特殊字符(覆盖上述行为)
  • 例如。 \. , \\ , \( , \? , \$ , \^

  • anchor 定模式:^匹配必须发生在字符串的开头
  • 例如。 ^a第一个字符必须是小写字母 a
  • 例如。 ^[0-9]第一个字符必须是数字。
  • $匹配必须出现在字符串的末尾
  • 例如。 a$最后一个字符必须是小写字母 a

  • 优先级表:
    Order  Name                Representation
    1      Parentheses         ( )
    2      Multipliers         ? + * {m,n} {m, n}?
    3      Sequence & Anchors  abc ^ $
    4      Alternation         |
    

    预定义的字符缩写:
    abr    same as       meaning
    \d     [0-9]         Any single digit
    \D     [^0-9]        Any single character that's not a digit
    \w     [a-zA-Z0-9_]  Any word character
    \W     [^a-zA-Z0-9_] Any non-word character
    \s     [ \r\t\n\f]   Any space character
    \S     [^ \r\t\n\f]  Any non-space character
    \n     [\n]          New line
    

    示例 1 : 作为宏运行
    以下示例宏查看单元格 A1 中的值查看前 1 或 2 个字符是否为数字。如果是,则删除它们并显示字符串的其余部分。如果没有,则会出现一个框,告诉您未找到匹配项。手机 A1 12abc 的值将返回 abc ,值 1abc将返回 abc ,值 abc123将返回“Not Matched”,因为数字不在字符串的开头。
    Private Sub simpleRegex()
        Dim strPattern As String: strPattern = "^[0-9]{1,2}"
        Dim strReplace As String: strReplace = ""
        Dim regEx As New RegExp
        Dim strInput As String
        Dim Myrange As Range
        
        Set Myrange = ActiveSheet.Range("A1")
        
        If strPattern <> "" Then
            strInput = Myrange.Value
            
            With regEx
                .Global = True
                .MultiLine = True
                .IgnoreCase = False
                .Pattern = strPattern
            End With
            
            If regEx.Test(strInput) Then
                MsgBox (regEx.Replace(strInput, strReplace))
            Else
                MsgBox ("Not matched")
            End If
        End If
    End Sub
    

    示例 2 : 作为内嵌函数运行
    此示例与示例 1 相同,但设置为作为单元内函数运行。要使用,请将代码更改为:
    Function simpleCellRegex(Myrange As Range) As String
        Dim regEx As New RegExp
        Dim strPattern As String
        Dim strInput As String
        Dim strReplace As String
        Dim strOutput As String
        
        
        strPattern = "^[0-9]{1,3}"
        
        If strPattern <> "" Then
            strInput = Myrange.Value
            strReplace = ""
            
            With regEx
                .Global = True
                .MultiLine = True
                .IgnoreCase = False
                .Pattern = strPattern
            End With
            
            If regEx.test(strInput) Then
                simpleCellRegex = regEx.Replace(strInput, strReplace)
            Else
                simpleCellRegex = "Not matched"
            End If
        End If
    End Function
    
    将您的字符串(“12abc”)放在单元格中 A1 .输入此公式 =simpleCellRegex(A1)在单元格中 B1结果将是“abc”。
    results image

    示例 3 : 循环范围
    此示例与示例 1 相同,但会循环遍历一系列单元格。
    Private Sub simpleRegex()
        Dim strPattern As String: strPattern = "^[0-9]{1,2}"
        Dim strReplace As String: strReplace = ""
        Dim regEx As New RegExp
        Dim strInput As String
        Dim Myrange As Range
        
        Set Myrange = ActiveSheet.Range("A1:A5")
        
        For Each cell In Myrange
            If strPattern <> "" Then
                strInput = cell.Value
                
                With regEx
                    .Global = True
                    .MultiLine = True
                    .IgnoreCase = False
                    .Pattern = strPattern
                End With
                
                If regEx.Test(strInput) Then
                    MsgBox (regEx.Replace(strInput, strReplace))
                Else
                    MsgBox ("Not matched")
                End If
            End If
        Next
    End Sub
    

    示例 4 : 分割不同的图案
    此示例循环遍历范围( A1A2A3 )并查找以三个数字开头、后跟单个字母字符和 4 个数字的字符串。输出使用 () 将模式匹配拆分为相邻的单元格. $1表示第一组 () 中匹配的第一个模式.
    Private Sub splitUpRegexPattern()
        Dim regEx As New RegExp
        Dim strPattern As String
        Dim strInput As String
        Dim Myrange As Range
        
        Set Myrange = ActiveSheet.Range("A1:A3")
        
        For Each C In Myrange
            strPattern = "(^[0-9]{3})([a-zA-Z])([0-9]{4})"
            
            If strPattern <> "" Then
                strInput = C.Value
                
                With regEx
                    .Global = True
                    .MultiLine = True
                    .IgnoreCase = False
                    .Pattern = strPattern
                End With
                
                If regEx.test(strInput) Then
                    C.Offset(0, 1) = regEx.Replace(strInput, "$1")
                    C.Offset(0, 2) = regEx.Replace(strInput, "$2")
                    C.Offset(0, 3) = regEx.Replace(strInput, "$3")
                Else
                    C.Offset(0, 1) = "(Not matched)"
                End If
            End If
        Next
    End Sub
    
    结果:
    results image

    其他模式示例
    String   Regex Pattern                  Explanation
    a1aaa    [a-zA-Z][0-9][a-zA-Z]{3}       Single alpha, single digit, three alpha characters
    a1aaa    [a-zA-Z]?[0-9][a-zA-Z]{3}      May or may not have preceding alpha character
    a1aaa    [a-zA-Z][0-9][a-zA-Z]{0,3}     Single alpha, single digit, 0 to 3 alpha characters
    a1aaa    [a-zA-Z][0-9][a-zA-Z]*         Single alpha, single digit, followed by any number of alpha characters
    
    </i8>    \<\/[a-zA-Z][0-9]\>            Exact non-word character except any single alpha followed by any single digit
    

    关于regex - 如何在单元格内和循环中使用 Microsoft Excel 中的正则表达式 (Regex),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22542834/

    相关文章:

    regex - 解析 git status 日志,如果修改的文件来自给定目录则退出

    excel - 从 Excel 的 VBA 调用加载项函数

    excel - 如何从非空白行单元格中获取顶行单元格文本

    c# - ExcelDataReader 数据类型 "date"被转换

    VBA MsgBox 导致错误

    excel - 在 Excel 中使用 TEXTJOIN 时如何消除重复项?

    javascript - 如何有选择地用 HTML 替换文本?

    regex - 在 Mac OS X 上使用 awk 匹配确切的单词

    正则表达式在字母数字字符串中查找未括在括号中的数字字符串

    java - 我的正则表达式模式中的误解