regex - 将多个匹配项返回到单个单元格中的 Excel VBA Regex 函数

标签 regex vba excel

我需要帮助才能使我的 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) 个匹配值到单个单元格(例如“Code 123 Code 4567”)。

非常感谢任何帮助!

最佳答案

看起来您错过了函数的结尾(根据 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

关于regex - 将多个匹配项返回到单个单元格中的 Excel VBA Regex 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44979363/

相关文章:

excel - 在 Excel VBA 中更改为加拿大 (CDN) 法语数字格式

Java POI删除单元格

excel - 电子表格中有无穷大吗?

正则表达式获取 data.table 中包含值的所有行?

php从文本字符串中剥离

excel - 如何将 Excel 工作表名称传递给 Access 子例程?

vba - 按行排序

vba - Excel vba Charting,编辑范围

javascript - 正则表达式验证字符的单次出现

Javascript 和 RegEx : match function returns an array