【问题标题】:Excel VBA - Multiple regex pattern deletionExcel VBA - 多个正则表达式模式删除
【发布时间】:2020-04-09 08:12:32
【问题描述】:

在 Excel VBA 中,我需要执行多个正则表达式匹配,然后从字符串中删除匹配项,同时保留字符串的其余部分。我通过菊花链连接两个变量来工作,并且不首先测试模式匹配,因为第二个匹配是第一个匹配的其余部分。

考虑以下数据:

(2.5.3) A. 100% 的产品将在 3 天内交付

(2.5.3) B. 空运产品的能力。

(2.5.3) C. 支持 xyz 功能

(2.5.3) D. 供应商应提供所提议的网络概览。

(2.5.3) E. 网络应该允许 CustomerABC 发现他们的设备。

(2.5.3) F. 应优化 CustomerABC 现有基础设施的使用。 CustomerABC 的能力会有所不同。

(2.5.3) G. 描述需要运行 CustomerABC 中心的网络设备数量。

使用这些数据,我将删除字符串开头的大纲数字,以及对 CustomerABC 的任何引用以及可能在字符串中的任何位置多次出现的任何连字符,可能是大写和小写。我有正则表达式的工作。这是我正在尝试的代码:

Function test(Txt As String) As String
Dim regEx As Object
Dim v1 As String
Dim v2 As String
Dim n As String
n = "CustomerABC"

If regEx Is Nothing Then
    Set regEx = CreateObject("VBScript.RegExp")
    regEx.Global = True
    regEx.IgnoreCase = True
End If
If Len(Txt) > 0 Then
    With regEx
    ' The 1st pattern
    .Pattern = "^\(?[0-9.]+\)?"
    'If Not .Test(Txt) Then Exit Function
    v1 = .Replace(Txt, "")
    ' The 2nd pattern
    .Pattern = n + "(\S*)?(\s+)?"
    'If Not .Test(Txt) Then Exit Function
    v2 = .Replace(v1, "")
 ' The result
   test = Application.Trim(v2)
   End With
  End If
End Function

有没有办法让它变得更好,加快速度,并有可变数量的匹配/删除?

提前致谢。

【问题讨论】:

  • 你可以传入一个模式数组以及要修改的字符串,或者在你的函数中定义一个数组,然后循环遍历它并执行替换。
  • 嗨,蒂姆,我看到了你的帖子:stackoverflow.com/questions/9672436/…,但由于我正在删除和保留剩余部分,我不确定如何使其适应我的特殊需求。我可以举个例子吗?

标签: excel vba


【解决方案1】:

像这样:

Function test(Txt As String) As String
    Static regEx As Object '<< need Static here
    Dim rv As String, p, n

    n = "CustomerABC"

    If regEx Is Nothing Then
        Set regEx = CreateObject("VBScript.RegExp")
        regEx.Global = True
        regEx.IgnoreCase = True
    End If
    If Len(Txt) > 0 Then
        rv = Txt
        'looping over an array of patterns
        For Each p In Array("^\(?[0-9.]+\)?", n & "(\S*)?(\s+)?")
            With regEx
                .Pattern = p
                rv = .Replace(rv, "")
            End With
        Next p
    End If
    test = Application.Trim(rv)
End Function

【讨论】:

  • 轰隆隆!非常感谢蒂姆。
猜你喜欢
  • 2012-01-14
  • 1970-01-01
  • 2022-10-05
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 2016-01-13
  • 1970-01-01
相关资源
最近更新 更多