How to change case of matching letter with a VBA regex Replace?

前端 未结 2 1924
余生分开走
余生分开走 2021-01-25 01:40

I have a column of lists of codes like the following.

2.A.B, 1.C.D, A.21.C.D, 1.C.D.11.C.D
6.A.A.5.F.A, 2.B.C.H.1
8.ABC.         


        
相关标签:
2条回答
  • 2021-01-25 01:47

    Here is a workaround that uses the properties of each individual regex match to make the VBA Replace() function replace only the text from the match and nothing else.

    Sub fixBlah2()
    Dim re As VBScript_RegExp_55.RegExp, Matches As VBScript_RegExp_55.MatchCollection
    Dim M As VBScript_RegExp_55.Match
    Dim tmpChr As String, pre As String, i As Integer
    Set re = New VBScript_RegExp_55.RegExp
    re.Global = True
    re.Pattern = "\b([1-5]\.[A-Z])\.([A-Z])\b"
    For Each c In Selection.Cells
        'Count of number of replacements made. This is used to adjust M.FirstIndex
        '    so that it still matches correct substring even after substitutions.
        i = 0
        Set Matches = re.Execute(c.Value)
        For Each M In Matches
            tmpChr = LCase(M.SubMatches.Item(1))
            If M.FirstIndex > 0 Then
                pre = Left(c.Value, M.FirstIndex - i)
            Else
                pre = ""
            End If
            c.Value = pre & Replace(c.Value, M.Value, M.SubMatches.Item(0) & tmpChr, _ 
                      M.FirstIndex + 1 - i, 1)
            i = i + 1
        Next M
    Next c
    End Sub
    

    For reasons I don't quite understand, if you specify a start index in Replace(), the output starts at that index as well, so the pre variable is used to capture the first part of the string that gets clipped off by the Replace function.

    0 讨论(0)
  • 2021-01-25 02:04

    So this question is old, but I do have another workaround. I use a double regex so to speak, where the first engine looks for the match as an execute, then I loop through each of those items and replace with a lowercase version. For example:

    Sub fixBlah()
    Dim re As VBScript_RegExp_55.RegExp
    dim ToReplace as Object
    Set re = New VBScript_RegExp_55.RegExp
    for each c in Selection.Cells
    with re      `enter code here`
      .Global = True
      .Pattern = "\b([1-5]\.[A-Z])\.([A-Z])\b"
      Set ToReplace = .execute(C.Value)
    end with
    
     'This generates a list of items that match.  Now to lowercase them and replace
     Dim LcaseVersion as string
     Dim ItemCt as integer
     for itemct = 0 to ToReplace.count - 1
     LcaseVersion = lcase(ToReplace.item(itemct))
          with re      `enter code here`
      .Global = True
      .Pattern = ToReplace.item(itemct)  'This looks for that specific item and replaces it with the lowercase version
      c.value = .replace(C.Value, LCaseVersion)
    end with
    End Sub
    

    I hope this helps!

    0 讨论(0)
提交回复
热议问题