Advertisement
3DotDev

Extraire chaîne de caractères dans du texte (ParseBetween)

Oct 26th, 2016
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 1.90 KB | None | 0 0
  1. '########################################################
  2. ' Credits 3DotDev from http://3dotdevcoder.blogspot.fr/
  3. '########################################################
  4.  
  5. Private Function ParseBetween(Source$, Before$, After$) As String()
  6.     Dim Results As New List(Of String)
  7.     Dim T As New List(Of String)
  8.     With T
  9.         .AddRange(System.Text.RegularExpressions.Regex.Split(Source, Before))
  10.         .RemoveAt(0)
  11.         For Each Item$ In T
  12.            Results.Add(System.Text.RegularExpressions.Regex.Split(Item, After)(0))
  13.         Next
  14.     End With
  15.     Return Results.ToArray
  16. End Function
  17.  
  18. Private Function ParseBetween(Source$, Before$, After$, Offset%) As String
  19.     If String.IsNullOrEmpty(Source) Then
  20.         Return String.Empty
  21.     End If
  22.     If Source.Contains(Before) = True Then
  23.         Dim Result$ = Source.Substring(Source.IndexOf(Before) + Offset)
  24.         If Result.Contains(After) = True Then
  25.             If Not String.IsNullOrEmpty(After) Then
  26.                 Result = Result.Substring(0, Result.IndexOf(After))
  27.             End If
  28.         End If
  29.         Return Result
  30.     Else
  31.         Return String.Empty
  32.     End If
  33. End Function
  34.  
  35.  
  36. '############################### Comment utiliser la première fonction qui retourne un tableau de String ###########################
  37.  
  38. 'On déclare une variable de type String et on y affecte du texte pour pouvoir le parcourir avec la fonction plus bas
  39. Dim TextToParse = "<div> <span id=""programme"">Programme TF1</span> <span>Mes infos</span> </div>" & vbNewLine & _
  40.                   "<div> <span id=""programme"">Programme fr2</span> <span>Mes infos</span> </div>"
  41.  
  42. 'Il peut exister plus occurences c'est pour cela qu'on utilise la fonction qui retourne un tableau de String
  43. For Each occur In ParseBetween(TextToParse, "<span id=""programme"">", "</span>")
  44.     MsgBox(occur)
  45. Next
  46.  
  47. 'Retourne les résultats suivants :
  48. 'Programme TF1
  49. 'Programme fr2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement