查找字符串中的所有字符串

时间:2016-02-06 10:25:39

标签: vba vbscript word-vba

我通过http请求响应文本将StrTxt作为html字符串。我想在StrTxt中找到所有出现的'“string”。

像这样。

for each string in StrTxt
StrTxt = "all matched strings from StrTxt"
do something StrTxt.

修改 这被标记为可能重复,但事实并非如此。 How to loop through each word in a word document - VBA Macro解释了如何在文档中查找字符串而不是字符串。

这很简单。如何用字符串查找所有字符串?我的头衔不是解释了一切吗?

修改2

从Ansgar Wiechers的回答中我试着跟随。

Do
i = InStr(strtxt, "startstring")
      If i > 0 Then
        strtxt = Mid(strtxt, i, Len(strtxt) - i)
        i = InStr(InStr(strtxt, "midstring") + 1, strtxt, "endstring")
        If i > 0 Then
         strtxt = Left(strtxt, i + Len(endstring)) ' I am using i+4 as I know the length
        WScript.Echo strtxt
        End If
      End If
Loop While i > 0

它只发生一次。如何正确循环?

3 个答案:

答案 0 :(得分:4)

如果您想使用InStr搜索字符串以查找特定子字符串的所有匹配项,则需要重复调​​用该函数,在最后一次匹配后开始每个新搜索(至少)一个字符。

response = "..."  'your HTTP response string
srch     = "..."  'the string you want to find in the response

start = 1
Do
  pos = InStr(start, response, srch, vbTextCompare)
  If pos > 0 Then
    start = pos + 1  'alternatively: start = pos + Len(srch)
    WScript.Echo pos
    WScript.Echo Mid(response, pos, Len(srch))
  End If
Loop While pos > 0

如果您希望比较区分大小写,请将vbTextCompare替换为vbBinaryCompare

编辑:要查找以某些字符串开头的模式,包含另一个字符串,以第三个字符串结尾,最好使用regular expression@TylerStandishMan已经在his answer中显示了基本原则,但在您的方案中有一些事情需要注意。

response = "..."  'your HTTP response string

startTerm = "startstring"
midTerm   = "midstring"
endTerm   = "endstring"

Set re = New RegExp
re.Pattern    = startTerm & "[\s\S]*?" & midTerm & "[\s\S]*?" & endTerm
re.Global     = True
re.IgnoreCase = True  'if required

For Each m In re.Execute(response)
  WScript.Echo m
Next

regular expression中的某些字符具有特殊含义(例如.匹配除换行符之外的任何字符),因此您需要确保开头,中间和结尾字词中的任何此类字符都正确转义(例如,使用\.匹配文字点)。如果要匹配的子字符串跨越多行,则需要表达式中与搜索项之间的任意文本匹配的部分,以包含换行符(例如[\s\S]以匹配任何空格或非空白字符)。您可能还希望将匹配设置为非贪婪,否则您将从第一次出现startTerm到最后一次出现endTerm时获得一次匹配。这就是修饰符*?的用途。

答案 1 :(得分:1)

通过使用ReplaceSplit,这很容易实现。

Option Explicit

Public Sub StringInString()

    Dim myString As String: myString = "This is my string. {This is another string.} How do I go about searching through this?"
    Dim findString As String: findString = "this"
    Dim var As Variant, mySplit As Variant
    Dim matchCount As Integer: matchCount = 0

    '    Remove any characters that aren't pure text, but leave spaces so we can split on those.
    Dim removeChars: removeChars = Array(".", ",", "/", "\", "|", "{", "}", "[", "]", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", ":", ";", """", "'", "<", ">", "?", "`", "~")

    For Each var In removeChars
        myString = Replace(myString, var, vbNullString)
    Next

    mySplit = Split(myString, " ")

    For Each var In mySplit
        If (LCase(findString) = LCase(var)) Then matchCount = matchCount + 1
    Next

End Sub

我不太清楚你期待什么作为你的输出,所以根据需要进行修改。

编辑:

更简单的解决方案,使用正则表达式(需要参考Micrsoft VBScript正则表达式5.5):

Public Sub StringInStringRegex()

    Dim myString As String: myString = "This is my string. {This is another string.} How do I go about searching through this?"

    Dim reg As New RegExp
    reg.Pattern = "(this)"
    reg.Global = True
    reg.IgnoreCase = True
    reg.MultiLine = True

    Dim Matches As MatchCollection
    Set Matches = reg.Execute(myString)

    Dim matchCount As Integer: matchCount = Matches.Count

End Sub

来源:How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loopsPattern match count in excel (regex & vba)

答案 2 :(得分:1)

使用动态数组和InStr函数尝试此注释示例:

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Find a string in a sentence
'Recherche d'une chaine de caractère dans une phrase
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Instruction Option Explicit: Force explicit declaration of all variables in a script
'Instruction Option Explicit: Force la déclaration explicite de toutes les variables dans un script
Option Explicit 
Dim Texte,sChaine
Texte = "This is my string. {This is another string.} How do I go about searching through this?" 
sChaine = "this"   'chaine recherchée
'Instruction Dim: Declares variables and allocates storage space
'Instruction Dim: Déclare des variables et alloue l'espace de stockage
Dim aPos() , iPos
'ReDim Statement: Declares the dynamic array of variables and attribute or
'Reallocates storage space at the procedure
'Table where positions are stored
'Instruction ReDim: Déclare les variables de tableau dynamique et attribue ou 
'réattribue l'espace de stockage au niveau de la procédure
'Tableau ou sont stockées les positions
ReDim aPos(0)  
'InStr Function: Returns the position of the first occurrence of a string
'In the interior of another
'Fonction InStr: Renvoie la position de la première occurrence d'une chaîne 
'à l'intérieur d'une autre
iPos = InStr(1, Texte, sChaine, vbTextCompare)  
'Instruction While ... Wend: Run a set of instructions as long as a given condition is True
'Instruction While...Wend: Exécute une série d'instructions tant qu'une condition donnée est True
    While iPos <> 0 
'UBound Function: Returns the largest available subscript for the indicated dimension of an array   
'Fonction UBound: Renvoie le plus grand indice disponible pour la dimension indiquée d'un tableau
        ReDim Preserve aPos(UBound(aPos) + 1) 
        aPos(UBound(aPos)) = iPos 
        iPos = InStr(iPos + 1, Texte, sChaine, vbTextCompare) 
    Wend 
'If ... Then ... Else Instruction: Executes a group of statements subject to a condition,
'In dependence of the value of an expression
'Instruction If...Then...Else: Exécute un groupe d'instructions soumises à une condition, 
'en fonction de la valeur d'une expression
    If UBound(aPos) > 0 Then 
        Dim i , Resultat 
        Resultat = "Occurrence """ & sChaine & """ found " & UBound(aPos) & " times " & _
                    "in the phrase" & vbCrLf & vbCrLf & """" & Texte & """" & vbCrLf & vbCrLf & _                   
                    "L'occurrence """ & sChaine & """ a été trouvée " & UBound(aPos) & " fois " &_
                   "dans l'expression " & vbCrLf & vbCrLf & """" & Texte & """" & vbCrLf 
'Instruction For ... Next: Repeats a group of statements a specified number of times
'CStr Function: Returns an expression that has been converted to a String subtype Variant
'Len Function: Returns the number of characters in a string
'Instruction For...Next: Répète un groupe d'instructions un nombre spécifié de fois
'Fonction CStr: Renvoie une expression qui a été convertie en un Variant de sous-type String
'Fonction Len: Renvoie le nombre de caractères contenus dans une chaîne
        For i = 1 To UBound(aPos) 
            Resultat = Resultat & vbCrLf & "Postion: " & CStr(aPos(i)) & "," & CStr(aPos(i)) + Len(sChaine)
        Next  
    Else     
        Resultat = "L'occurrence """ & sChaine & """ n'a pas été trouvée dans l'expression " &vbCrLf&vbCrLf&_
        """" & Texte & """"
    End If 
Wscript.echo Resultat