【问题标题】:Excel VBA Regex Function That Returns Multiple Matches Into A Single Cell将多个匹配项返回到单个单元格的 Excel VBA 正则表达式函数
【发布时间】:2017-12-12 06:12:39
【问题描述】:

我需要帮助才能让我的 Excel 函数正常工作。目标是运行一个单元内函数,将正则表达式函数的所有模式匹配从另一个单元格的输入提取到一个单元格中,而不是单元格数组。

我已经尝试过使用一个数组,该数组在函数对话框预览中返回两个匹配项,但只输出单元格中的第一个匹配项。我也尝试过使用集合,但没有运气。

这是我当前的代码和将用作函数的字符串输入的文本示例:

Function RegexMatches(strInput As String) As Variant

Dim rMatch As Match
Dim arrayMatches
Dim i As Long

arrayMatches = Array()

With New RegExp
    .Global = True
    .MultiLine = True
    .IgnoreCase = True
    .Pattern = "(Code)[\s][\d]{2,4}"
        For Each rMatch In .Execute(strInput)
        ReDim Preserve arrayMatches(i)
        arrayMatches(i) = rMatch.Value
        i = i + 1
    Next
End With

    RegexMatches = arrayMatches
End Function


Excel 单元格中的 strInput 示例:

代码 123 一些随机文本
到这里继续下一行
代码 4567 后跟更多文本
包括换行而不仅仅是换行的文本



此函数的所需输出将是 (2) 来自正则表达式函数的匹配值到 单个单元格(例如“代码 123 代码 4567”)。

非常感谢任何帮助!

【问题讨论】:

  • 连接匹配值,然后返回这个修剪后的字符串。
  • @Mat'sMug 看看这个screen shot
  • @WiktorStribiżew 这就是我在概念上的想法,但我不知道如何使用 VBA 代码在函数中做到这一点。
  • @Mat'sMug 感谢您的洞察力,我错过了复制/粘贴的最后三行。我现在就更正一下。

标签: regex vba excel


【解决方案1】:

看起来您错过了函数的结尾(根据 Mat's Mug 的评论)?试试这个(根据 Wiktor 的评论)。

编辑:根据 Mat's Mug 的建议进行了修改。

Function RegexMatches(strInput As String) As String

Dim rMatch As Object
Dim s As String
Dim arrayMatches()
Dim i As Long

With New RegExp
    .Global = True
    .MultiLine = True
    .IgnoreCase = True
    .Pattern = "(Code)[\s][\d]{2,4}"
    If .test(strInput) Then
        For Each rMatch In .Execute(strInput)
            ReDim Preserve arrayMatches(i)
            arrayMatches(i) = rMatch.Value
            i = i + 1
            's = s & " " & rMatch
        Next
    End If
End With

RegexMatches = Join(arrayMatches, " ")

End Function

【讨论】:

  • 我会让函数返回一个匹配数组,顾名思义(Variant 很好),并在调用站点使用Join 将值与vbNewLine 连接起来让字符串转储到单元格中。
  • @Mat'sMug - 谢谢,已修改。我同意这是一种更优雅的方法。
  • 除非你现在正在执行Join in 函数(返回一个String); RegexMatches = arrayMatches,让调用者处理字符串表示;-)
  • 哎呀,才发现这个函数实际上是作为一个UDF使用的!
  • 什么都没有——函数被单元调用的事实让我无法理解;在返回之前加入,并返回String,这正是 OP 需要的 =) 如果它只是一个普通函数,它负责匹配和字符串表示将违反 SRP IMO。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多