通过搜索改进excel RegExp用户功能并按列表替换

时间:2017-01-28 18:25:22

标签: regex excel vba excel-vba regexp-replace

我在excel中有简单的vba用户函数,用RegEx在文本中替换:

Function RegExReplace (SearchPattern As String, TextToSearch As String, _
                          ReplacePattern As String, _
                          Optional GlobalReplace As Boolean = True, _
                          Optional IgnoreCase As Boolean = False, _
                          Optional MultiLine As Boolean = False) As String
    Dim RE As Object
    
    Set RE = CreateObject ( "vbscript.regexp")
    With RE
        .MultiLine = MultiLine
        .Global = GlobalReplace
        .IgnoreCase = IgnoreCase
        .Pattern = SearchPattern
    End With
    
    RegExReplace = RE.Replace (TextToSearch, ReplacePattern)
        
End Function

但它只能搜索和替换一个

- 搜索模式(在单元格C2中)和一个 - 替换模式(在单元格D2中)

所以,我想要的 - 当单元格C2中的模式没有匹配时 - 它需要搜索并替换单元格C3和D3中的模式。

enter image description here

更真实的例子的屏幕截图 enter image description here

之前我发布的代码替换为RegEx模式列表,我认为它可能有所帮助:

Sub regexpreplace ()

    Set Myrange = ActiveSheet.Range ( "A2: A1000") 'range in which we make replace
    Set regrange = ActiveSheet.Range ( "B2: B6") 'range with RegExp pattern
    'In range C1: C6 we have pattern for replace
    
    For Each D In regrange        
        For Each C In Myrange
            Set rgx = CreateObject ( "VBScript.RegExp")
            rgx.IgnoreCase = True
            rgx.Pattern = D.Value
            rgx.Global = True
            C.Value = rgx.Replace (C.Value, D.Offset (0, 1) .Value)
        Next
    
    Next

End Sub

在此代码中:

A1:A1000 - 输入值范围

B1:B6 - RegExp模式列表

C1:C6 - 输出模式列表

那么,当单元格C2与模式没有匹配时我怎么能 - 它需要搜索并替换单元格C3和D3中的模式?

1 个答案:

答案 0 :(得分:1)

当然有一种方法可以检查正则表达式是否匹配,并在必要时检查另一个正则表达式,但为什么不使用匹配这两种情况的正则表达式呢?

E.g。下面这个选择两个场景中的第二个数字:

  • 正则表达式:.* \d+x(\d+)x?.*
  • 替换为:\1

测试here

对于您的原始问题,要更改正则表达式,您可以使用以下内容:

Sub regexpreplace()
    Dim Rgx As RegExp
    Dim MyRange As Range
    Dim RegRange As Range
    Dim C As Range
    Dim D As Range

    Set MyRange = ActiveSheet.Range("A2: A1000")   'range in which we make replace
    Set RegRange = ActiveSheet.Range("B2: B6")   'range with RegExp pattern
    'In range C1: C6 we have pattern for replace

    Set Rgx = CreateObject("VBScript.RegExp")
    Rgx.IgnoreCase = True
    Rgx.Global = True

    For Each C In MyRange
        rgxrow = 1
        Do
            Rgx.Pattern = RegRange.Cells(rgxrow, 1)
            If Rgx.Test(C) Then
                C.Value = Rgx.Replace(C.Value, RegRange(rgxrow, 2))
                rgxrow = D.Rows.Count + 1
            Else
                rgxrow = rgxrow + 1
            End If
        Loop Until rgxrow > D.Rows.Count
    Next C
End Sub