VB.NET-它不断替换自己 [英] VB.NET - It keep replacing itself

查看:72
本文介绍了VB.NET-它不断替换自己的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文本文件中有以下格式的行:

I have in a text file lines of this format:

word1|word2|word3
anotherword1|anotherword2

我正尝试在文件的每一行中将每个单词一一拆分,一旦程序检测到richtextbox是否包含这些单词之一,就会将该单词替换为未拆分的行.示例:从word1到word1 | word2 | word3

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

它很好用,但是在替换后,替换的文本仍然具有检测到的单词,并且永远永远用word1 | word2 | word3替换自身.我只想做一次.

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.

像这样:单击以查看

推荐答案

由于单词存储的格式,使用正则表达式可以轻松实现您想要的目标:

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.

这篇关于VB.NET-它不断替换自己的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆