Excel VBA-字符串替换-reg exp?

时间:2018-08-01 09:15:00

标签: excel vba excel-vba

我正在Excel VBA中进行一些单词替换。替换单词本身,用任何特殊字符(a-z,A-Z,0-9除外)分隔,并保留大小写。

正确替换示例(将example替换为replaced):

One example string> One replaced string

One Example string> One Replaced string

One Example, string> One Replaced, string

One >example< string> One >replaced< string(前面和后面的特殊字符)

One dexamples string> One dexamples stringexample未替换)

我通过使用服务器线使它正常工作,如下所示。有什么想法如何使用正则表达式或类似方法做到这一点?

cel.Replace what:=" " & Rng.Value & " ", replacement:=" " & Rng.Offset(0, 1).Value & " ", MatchCase:=True
cel.Replace what:=" " & Rng.Value & ",", replacement:=" " & Rng.Offset(0, 1).Value & ",", MatchCase:=True
cel.Replace what:=">" & Rng.Value & "<", replacement:=">" & Rng.Offset(0, 1).Value & "<", MatchCase:=True
...

编辑: 我有大约1000个单词的列表,这些单词应通过脚本运行,并单独替换。因此,我需要将该案例作为变量输入。 (如果匹配项为Example,则替换项必须为Replaced

编辑: 有一些服务器特殊字符要处理。例如:“,。/ \”?()<>;:&“。该列表已经很长了。

3 个答案:

答案 0 :(得分:1)

尝试以下代码,无需使用正则表达式:

str = Cells(rowNumber, columnNumber).Value
str = Replace(str, " example", " replaced")
str = Replace(str, " Example", " Replaced")
str = Replace(str, ">example", ">replaced")
str = Replace(str, ">Example", ">Replaced")
Cells(rowNumber, columnNumber).Value = str

答案 1 :(得分:0)

或使用正则表达式模式

\b[E|e]xample\b

正则表达式:

Regex

Try it


VBA:

Option Explicit
Public Sub test()
    Dim arr(), i As Long
    arr = Array("One dexamples string", "One example string", "One >example< string", "One Example, string", "One Example string", "One example string")
    For i = LBound(arr) To UBound(arr)
        Debug.Print ReplaceMatch(arr(i), "\b[E|e]xample\b")
    Next i
End Sub
Public Function ReplaceMatch(ByVal inputString As String, ByVal pattern As String) As String
    Dim re As Object
    Set re = CreateObject("VBScript.RegExp")
    With re
        .Global = True
        .MultiLine = True
        .pattern = pattern

        If .test(inputString) Then
            ReplaceMatch = .Replace(inputString, "replaced")
        Else
            ReplaceMatch = inputString
        End If
    End With
End Function

这需要对Case测试进行一些开发:

Option Explicit

Public Sub test()
    Dim arr(), i As Long
    arr = Array("One dexamples string", "One example string", "One >example< string", "One Example, string", "One Example string", "One example string")
    For i = LBound(arr) To UBound(arr)
      Debug.Print ReplaceMatch(arr(i), "\b[E|e]xample\b")
    Next i
End Sub
Public Function ReplaceMatch(ByVal inputString As String, ByVal pattern As String) As String
    Dim re As Object
    Set re = CreateObject("VBScript.RegExp")
    With re
        .Global = True
        .MultiLine = True
        .pattern = pattern

        If .test(inputString) Then
            If AscW(Left$(.Execute(inputString)(0), 1)) < 91 Then
                ReplaceMatch = .Replace(inputString, "Replaced")
            Else
                ReplaceMatch = .Replace(inputString, "replaced")
            End If
        Else
            ReplaceMatch = inputString
        End If
    End With
End Function

答案 2 :(得分:0)

如果您的大小写可变性仅涉及单词的第一个字母,那么下面的代码将做到这一点。

如果单词中的大小写可能混合使用,则需要逐个字母地循环浏览,并且还决定替换的长度与找到的单词的长度不同时该怎么做< / em>

此代码潜在的问题:

  • \b是单词边界标记。
  • 单词边界被定义为一个位置,该位置的一侧由单词标记限定,另一侧由非单词标记或字符串的开头/结尾限定。
  • 单词令牌是[A-Za-z0-9_]集中的任何内容
  • 因此,如果您的源代码中包含以_(下划线)开头或结尾的字符串,则不会找到它们。
  • 如果这可能是一个问题,我们将不得不更改正则表达式,以及在何处查找“大小写”字符,或者只是将下划线临时替换为其他非单词字符(然后在之后将其改回) 。

Option Explicit
'Set reference to Microsoft VBScript Regular Expressions 5.5
'   or use late binding
Function CSReplace(S As String, sFind As String, sRepl As String) As String
    Dim RE As RegExp, MC As MatchCollection, M As Match
    Dim sTemp As String, I As Long

Set RE = New RegExp
With RE
    .Global = True
    .IgnoreCase = True
    .Pattern = "\b" & sFind & "\b"
    If .Test(S) = True Then
        Set MC = .Execute(S)
        sTemp = S
        For I = MC.Count - 1 To 0 Step -1
            Set M = MC(I)
            sRepl = LCase(sRepl)
            If Left(M, 1) = UCase(Left(M, 1)) Then _
                sRepl = UCase(Left(sRepl, 1)) & Mid(sRepl, 2)
            sTemp = WorksheetFunction.Replace(sTemp, M.FirstIndex + 1, Len(sFind), sRepl)
        Next I
        CSReplace = sTemp
    Else
        CSReplace = S
    End If
End With

End Function

enter image description here