VB.NET - 它不断更换自己
VB.NET - It keep replacing itself
我在文本文件中有以下格式的行:
word1|word2|word3
anotherword1|anotherword2
我正在尝试将该文件的每一行一个一个地拆分每个单词,一旦程序检测到 richtextbox 是否有这些单词之一,就会用未拆分的行替换该单词。示例:从 word1 到 word1|word2|word3
这是我目前的情况:
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
效果很好,但是在替换之后,被替换的文本仍然有检测到的单词,并且它会永远用 word1|word2|word3 替换自己。我只想做一次这个过程。
像这样:Click to see
由于单词的存储格式,使用正则表达式可以更轻松地实现您想要的效果:
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
这应该可以满足您的需求。
检查一下here。
我在文本文件中有以下格式的行:
word1|word2|word3
anotherword1|anotherword2
我正在尝试将该文件的每一行一个一个地拆分每个单词,一旦程序检测到 richtextbox 是否有这些单词之一,就会用未拆分的行替换该单词。示例:从 word1 到 word1|word2|word3
这是我目前的情况:
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
效果很好,但是在替换之后,被替换的文本仍然有检测到的单词,并且它会永远用 word1|word2|word3 替换自己。我只想做一次这个过程。
像这样:Click to see
由于单词的存储格式,使用正则表达式可以更轻松地实现您想要的效果:
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
这应该可以满足您的需求。
检查一下here。