如何搜索字符串并动态替换特定单词? [英] How do I search through a string and replace specific words dynamically?
问题描述
我正在努力在显示富文本框中的所有文本之前替换文本中的单词。我遇到的问题是代码似乎是通过循环重复,而不是批量文本替换。
这是我的代码:
文本文件路径连接字符串
sql连接使用select *来填充datata表(repdt)
I am working on replacing words in a text before showing all text in a richtextbox. The issue I am having is that the code seems to be reiterating through the loop, instead of a bulk text replacement.
here is my code:
text file path connection string
sql connection with using select * to fill datata table(repdt)
For Each textpath As String In Files.FileNames
RichTextBox1.Clear()
Dim newline = String.Empty
Dim regstr = String.Empty
For I As Integer = 0 To repdt.Rows.Count - 1
For Each line As String In File.ReadLines(textpath)
If line.Contains(repdt.Rows(I).Item("originaltext").ToString) Then
newline = line.Replace(repdt.Rows(I).Item("originaltext"), repdt.Rows(I).Item("replacementtext"))
regstr = String.Join(Environment.NewLine, line.Split(New Char() {ControlChars.Lf}, StringSplitOptions.RemoveEmptyEntries)).Replace(vbTab, "")
RichTextBox1.Text += newline + Environment.NewLine
End If
Next
Next
我正在尝试把它变成一个库或文本来代替。
我尝试过:
最初,我使用它:
I am trying to make this into a library or text to replace.
What I have tried:
Initially, I was using this:
For Each textpath As String In Files.FileNames
RichTextBox1.Clear()
Dim regstr As String = String.Join(Environment.NewLine, System.IO.File.ReadAllText(textpath).Split(New Char() {ControlChars.Lf}, StringSplitOptions.RemoveEmptyEntries))
Dim replacestr As String = regstr.Replace("text", "text").Replace("text", "text").Replace("text", "text"). 'etc
RichTextBox1.Text = replacestr
Next
但是,这个每当我想要替换某些东西时都需要编码。
however, this requires coding everytime I want to replace something.
推荐答案
这是我对它的看法。
Here's my take on it.
For Each textpath As String In Files.FileNames
RichTextBox1.Clear()
Dim newline = String.Empty
Dim regstr = String.Empty
//Process each line in the file once
For Each line As String In File.ReadLines(textpath)
newline = line
//apply each replacement rule to the result of the previous replacement rule
For I As Integer = 0 To repdt.Rows.Count - 1
If newline.Contains(repdt.Rows(I).Item("originaltext").ToString) Then
newline = newline.Replace(repdt.Rows(I).Item("originaltext"), repdt.Rows(I).Item("replacementtext"))
//hold over code?
//regstr = String.Join(Environment.NewLine, newline.Split(New Char() {ControlChars.Lf}, StringSplitOptions.RemoveEmptyEntries)).Replace(vbTab, "")
End If
Next
//remove linefeeds and tabs
newline=newline.Replace(Environment.NewLine,"").Replace(vbTab, "")
//after all rules, add final result to the textbox
if newline.TrimEnd().Length>0 then
RichTextBox1.Text += newline + Environment.NewLine
end if
Next
这篇关于如何搜索字符串并动态替换特定单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!