VBA Excel如果在字符串开头出现数字,请替换数字的最后两位

时间:2019-01-22 20:16:47

标签: regex excel vba pattern-matching

如果数字的后两位出现在字符串的开头并且超过两位,我正在尝试用“ XX BLOCK”替换数字的后两位。

我正在使用 Microsoft VBScript正则表达式5.5 参考。

Dim regEx As New RegExp
With regEx
    .Global = True 'Matches whole string, not just first occurrence
    .IgnoreCase = True 'Matches upper or lowercase
    .MultiLine = True 'Checks each line in case cell has multiple lines
    .pattern = "^(\d{2,})" 'Checks beginning of string for at least 2 digits
End With

'cell is set earlier in code not shown, refers to an Excel cell
regEx.replace(cell.Value, "XX BLOCK")

所需结果:

"1091 foo address"      --> "10XX BLOCK foo address"
"1016 foo 1010 address" --> "10XX BLOCK foo 1010 address"
"foo 1081 address"      --> "foo 1081 address"
"10 bar address"        --> "XX BLOCK bar address"
"8 baz address"         --> "8 baz address"

我是regex的新手,不确定从哪里开始。我尝试使用^(\d{2,}),但随后它替换了整个数字。

还保证数字(如果存在)将始终 后跟空格。

2 个答案:

答案 0 :(得分:4)

您可以使用

^(\d*)\d{2}\b

或者,如果您不能依赖单词边界,也可以使用

^(\d*)\d{2}(?!\d) ' no digit is allowed after the 2-digit sequence
^(\d*)\d{2}(?!\S) ' a whitespace boundary

并替换为$1XX BLOCK

请参见regex demo

详细信息

  • ^-字符串的开头
  • (\d*)-第1组:零个或多个数字
  • \d{2}-两位数字
  • \b-两个数字之后的字边界,不允许有数字,字母或_
  • (?!\d)-如果当前位置的右侧紧邻有一个数字,则负向超前将导致匹配失败
  • (?!\S)-如果当前位置的右侧紧邻有非空白字符,则负向超前将使匹配失败。

答案 1 :(得分:2)

https://regex101.com/r/M1QrPZ/1

Pattern = "^\d{2}(\d{2})"

尝试以下

Option Explicit
Private Sub Example()
    Dim RegExp As New RegExp
    Dim Pattern As String
    Dim rng As Range
    Dim Cel As Range

    Set rng = ActiveWorkbook.Sheets("Sheet1" _
                            ).Range("A1", Range("A9999" _
                            ).End(xlUp))


    Dim Matches As Variant
    For Each Cel In rng
        DoEvents
        Pattern = "^\d{2}(\d{2})"

        If Pattern <> "" Then
            With RegExp
                .Global = True
                .MultiLine = True
                .IgnoreCase = False
                .Pattern = Pattern
                 Set Matches = .Execute(Cel.Value)
            End With

            If Matches.Count > 0 Then
                Debug.Print Matches(0) ' full mach
                Debug.Print Matches(0).SubMatches(0) ' sub match
               Cel.Value = Replace(CStr(Cel), Matches(0).SubMatches(0), "XX BLOCK")
            End If
        End If

    Next
End Sub