从特定字符串开头和结尾的字符串中提取文本

时间:2014-07-02 10:00:57

标签: vba

嗨我有下面的代码,它是从支架中提取字符串,它的确定但现在我发现有时在我的字符串中它可以是更多括号支持文本背后我需要提取它们到例如列表或表格如何做到这一点?

e.g hsus(irt)bla dsd (got)(rifk)

我需要:irt,得到,rifk列出怎么做?

Public Function extract_value(str As String) As String
dim str as string
dim openPos as integer
dim closePos as integer
dim midBit as string

str = "sometinhf(HELLO)sds"
openPos = instr (str, "(")
closePos = instr (str, ")")
midBit = mid (str, openPos+1, closePos - openPos - 1)
End Function

2 个答案:

答案 0 :(得分:2)

Sub Main()

    Dim s$
    s = "hsus(irt)bla dsd (got)(rifk)"

    Debug.Print extract_value(s)

End Sub

Public Function extract_value$(s$)

    Dim returnS$
    Dim v
    v = Split(s, Chr(40))

    For Each Item In v
        If InStr(Item, Chr(41)) Then
            returnS = returnS & Chr(32) & Split(Item, ")")(0)
        End If
    Next

    extract_value = Trim$(returnS)
End Function

答案 1 :(得分:0)

您可以使用Regexp直接提取匹配的字符串

Sub Main()
    Dim strTest as string
    strTest = "hsus(irt)bla dsd (got)(rifk)"
    MsgBox GrabIt(strTest)
End Sub

Function GrabIt(strIn As String) As String
Dim objRegex As Object
Dim objRegMC As Object
Dim objRegM As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "\((.*?)\)"
.Global = True
    If .test(strIn) Then
    Set objRegMC = .Execute(strIn)
        For Each objRegM In objRegMC
        GrabIt = GrabIt & Chr(32) & objRegM.submatches(0)
        Next
    End If
End With
End Function