正则表达式删除以某个字符串开头的所有内容,然后是其他内容?

时间:2017-08-05 03:51:35

标签: excel excel-vba vba

代码正在运行但它没有循环遍历每一行以将答案放在其相邻列中。所有列B都得到了最后一行的答案。

enter image description here

Private Sub simpleRegex()
'Dim strPattern As String: strPattern = "^[0-9]{1,2}"
Dim strPattern As String: strPattern = "BSU:.*"
Dim strReplace As String: strReplace = ""
Dim regEx As New RegExp
Dim strInput As String
Dim Myrange As range
Dim r As range
Set r = ActiveSheet.range("A1", range("A1").End(xlDown))
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
            r.Offset(0, 1).Value = (regEx.Replace(strInput, strReplace))


            'MsgBox (regEx.Replace(strInput, strReplace))
        Else
            'MsgBox ("Not matched")
        End If
    End If
Next
End Sub

1 个答案:

答案 0 :(得分:1)

模式*中的BSU:*仅应用于前一个字符,因此它会匹配: 0或多次。

匹配以BSU:开头的字符串,然后使用

BSU:.*

在这种情况下.匹配任何字符,而.*匹配任何字符0次或更多次,这是您需要的,除非您只想匹配之后的 em> BSU:也可以完成(前瞻或捕获组)。