VBA Excel替换数字的最后2位数字(如果出现在字符串的开头)

VBA Excel Replace last 2 digits of number if occurs at beginning of string

提问人:sushi 提问时间:1/23/2019 最后编辑:0m3rsushi 更新时间:1/23/2019 访问量:917

问:

我正在尝试将数字的最后两位数字替换为“”,如果它出现在字符串的开头并且有超过 2 位数字。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"

我是正则表达式的新手,不知道从哪里开始。我尝试使用,但后来它替换了整个数字。^(\d{2,})

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

正则表达式 Excel VBA 模式匹配

评论


答:

4赞 Wiktor Stribiżew 1/23/2019 #1

您可以使用

^(\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

请参阅正则表达式演示

  • ^- 字符串的开头
  • (\d*)- 第 1 组:零位或多位数字
  • \d{2}- 两位数
  • \b- 单词边界,不允许在两位数字之后使用字母、字母或_
  • (?!\d)- 如果当前位置右侧有一个数字,则负前瞻将失败,如果当前位置右侧有一个数字,则无法匹配
  • (?!\S)- 如果当前位置右侧有非空格字符,则否定前瞻,如果紧挨着当前位置的右侧,则匹配失败。

评论

0赞 Mathieu Guindon 1/23/2019
但是,不确定 VBScript 风格的正则表达式是否支持前瞻。
1赞 Wiktor Stribiżew 1/23/2019
支持@MathieuGuindon Lookaheads。Lookbehinds 不是。
2赞 0m3r 1/23/2019 #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