par , 18/11/2016 à 20h56 (832 Affichages)
Il existe 2 fonctions bien pratiques pour obtenir du texte contenu entre 2 balises :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
Private Function ParseBetween(Source$, Before$, After$) As String()
Dim Results As New List(Of String)
Dim T As New List(Of String)
With T
.AddRange(System.Text.RegularExpressions.Regex.Split(Source, Before))
.RemoveAt(0)
For Each Item$ In T
Results.Add(System.Text.RegularExpressions.Regex.Split(Item, After)(0))
Next
End With
Return Results.ToArray
End Function
Private Function ParseBetween(Source$, Before$, After$, Offset%) As String
If String.IsNullOrEmpty(Source) Then
Return String.Empty
End If
If Source.Contains(Before) = True Then
Dim Result$ = Source.Substring(Source.IndexOf(Before) + Offset)
If Result.Contains(After) = True Then
If Not String.IsNullOrEmpty(After) Then
Result = Result.Substring(0, Result.IndexOf(After))
End If
End If
Return Result
Else
Return String.Empty
End If
End Function |
Dans le cas où plusieurs occurrences seront probablement trouvées dans le contenu à parser il faut utiliser la fonction qui retourne un tableau de String (la 1ère fonction) :
En partant du principe que tu veux obtenir le "Mes infos" de la chaîne "Programme TF1" (nom que tu connais déjà préalablement) :
1 2 3 4 5 6 7
| Dim TextToParse = "<div> <span id=""programme"">Programme TF1</span> <span>Mes infos</span> </div>" & vbNewLine &
"<div> <span id=""programme"">Programme fr2</span> <span>Mes infos</span> </div>"
Dim Result() As String = ParseBetween(TextToParse, "<span id=""programme"">Programme TF1</span> <span>", "</span>")
For Each occur In Result
MsgBox(occur)
Next |
Tu peux parcourir le texte pour obtenir le nom des chaînes :
1 2 3 4 5 6 7
| Dim TextToParse = "<div> <span id=""programme"">Programme TF1</span> <span>Mes infos</span> </div>" & vbNewLine &
"<div> <span id=""programme"">Programme fr2</span> <span>Mes infos</span> </div>"
Dim Result() As String = ParseBetween(TextToParse, "<span id=""programme"">", "</span>")
For Each occur In Result
MsgBox(occur)
Next |
A+