Excel - 从单元格中提取模式匹配后所有出现的字符串模式+后续的4个字符

时间:2014-02-05 14:40:47

标签: regex excel vba excel-vba

我正在努力处理一个巨大的Excel表格,我需要从某个单元格中提取(A1), 所有出现的字符串模式,例如“TCS”+模式匹配后的以下4个字符,例如TCS1234以逗号分隔成另一个单元格(B1)。

示例:

Cell A1包含以下字符串:

HRS164, SRS3439(s), SRS3440(s), SRS3441(s), SRS3442(s), SRS3443(s), SRS3444(s), SRS3445(s), SRS3449(s), SRS3450(s), SRS3451(s), SRS3452(s), SYSBASE.SSS300(s), TCS3715(s), TCS3716(s), TCS3717(s), TCS4037(s), TCS1234

所有TCS编号应在B1中以逗号分隔:

TCS3715, TCS3716, TCS3717, TCS4037, TCS1234

没有必要提取后面的“(s)”。

有人可以帮助我(excel新秀)应对这一挑战吗?

TIA Erika

3 个答案:

答案 0 :(得分:1)

以下是我将使用的内容:用户定义的函数:

Function GetTCS(TheString)
    For Each TItem In Split(TheString, ", ")
        If Left(TItem, 3) = "TCS" Then GetTCS = GetTCS & TItem & " "
    Next
    GetTCS = Replace(Trim(GetTCS), " ", ", ")
End Function

这将从您的字符串中返回“TCS3715(s),TCS3716(s),TCS3717(s),TCS4037(s),TCS1234”。如果你不知道如何创建一个用户定义的函数,那么问一下,这很简单,我很乐意向你展示。希望这会有所帮助。

答案 1 :(得分:0)

尝试以下用户定义函数:

Public Function Xtract(r As Range) As String
    Dim s As String, L As Long, U As Long
    Dim msg As String, i As Long
    s = Replace(r(1).Text, " ", "")
    ary = Split(s, ",")
    L = LBound(ary)
    U = UBound(ary)
    Xtract = ""
    msg = ""
    For i = L To U
        If Left(ary(i), 3) = "TCS" Then
            If msg = "" Then
                msg = Left(ary(i), 7)
            Else
                msg = msg & "," & Left(ary(i), 7)
            End If
        End If
    Next i
    Xtract = msg
End Function

答案 2 :(得分:0)

如果TCS部分总是在示例中的字符串末尾,我会使用(在B1中):

= REPLACE(A1,1,FIND( “TCS”,A1)-1 “”)