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 31 32 33 34 35
|
Try
'Chemin du fichier texte
Dim fPath = "D:\Bureau\regex.txt"
'Pattern du commentaire sur une ligne
Dim LineCommentspattern = "//(.*?)$"
'Contenu du fichier texte modifié
Dim txt As String = String.Empty
'On déclare un streamreader pour lire le fichier texte
Using sr As New StreamReader(fPath, System.Text.Encoding.Default)
'On lit le fichier jusqu'à la fin du flux
Do While Not sr.EndOfStream
'On récupère la ligne en cours de lecture dans la variable Str
Dim str As String = sr.ReadLine
'On concatène chaque ligne lu afin stocker chaque changement dans la variable txt
txt &= str & vbNewLine
'On capture toutes les correspondances du pattern sur la ligne en cours de lecture (retourne une collection)
Dim matches = Regex.Matches(str, LineCommentspattern, RegexOptions.Singleline)
If matches.Count <> 0 Then
'On parcours chaque correspondance
For Each m As Match In matches
'On remplace la correspondance trouvée (m.value) par une valeur vide
txt = txt.Replace(m.Value, String.Empty)
Next
End If
Loop
'On ferme le fichier en cours de lecture
sr.Close()
End Using
'On écrit le contenu de la variable txt dans le même fichier
My.Computer.FileSystem.WriteAllText(fPath, txt, False)
Catch ex As Exception
MsgBox(ex.ToString)
End Try |