使用Regex查找和删除字符串-但保留最后一个字符

时间:2019-03-18 20:08:22

标签: excel vba

我想在下面找到“ strPattern”字符串,但是使用REPLACE仅替换“ strPattern1”-实际上是“ strPattern”,不包括最后一个字符。

Dim strPattern As String: strPattern = "^\d{1,2}.\d{1,2}\s\OS\s[MCVH]"

Dim strPattern1 As String: strPattern1 = "^\d{1,2}.\d{1,2}\s\OS"

Dim strReplace As String: strReplace = ""
Dim regEx As New RegExp
Dim strInput As String
Dim Myrange As Range

Set Myrange = ActiveSheet.Range("B1", Range("b1").End(xlDown))

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
            cell.Offset(0, 0) = regEx.Replace(strInput, strReplace)
        End If
    End If
Next

预先感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您需要使用搜索字符串'()'中的字段。例如“((^ \ d {1,2}。\ d {1,2} \ s \ OS \ s)([MCVH])”。您的替换字符串为“ $ 2”。