VB.NET - It keep replacing itself

2019-04-03 01:46发布

问题:

I have in a text file lines of this format:

word1|word2|word3
anotherword1|anotherword2

I'm trying to split each word one by one per every line of that file and once program detect if the richtextbox has one of these words will replace that word with the unsplitted line. Example: From word1 to word1|word2|word3

Here is what I have so far:

Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    For Each line As String In File.ReadLines("C:\text.txt")
        Dim input As String = line
        Dim result As String() = line.Split(New String() {"|"}, StringSplitOptions.None)
        For Each s As String In result
            Try
                Dim linex As String = line
                RichTextBox1.Text = RichTextBox1.Text.Replace(s, " " & linex)
            Catch exxx As Exception
            End Try
        Next
    Next
End Sub

It works great, but after the replacement, the replaced text still have the detected word and it keep replacing itself with word1|word2|word3 forever. And I want do do the process just once.

Like this: Click to see

回答1:

Due to the format the words are stored in, it will be much easier to achieve what you want using Regular Expressions:

Dim lines = File.ReadLines("C:\text.txt")
For Each line As String In lines
    Dim pat = String.Format("\b({0})\b", line)
    RichTextBox1.Text = Regex.Replace(RichTextBox1.Text, pat, line)
Next

This should do pretty much what you want.

Check it here.