繁体   English   中英

c#如何根据文件中的正则表达式模式进行替换

[英]c# How to proceed replacements based on regex patterns from the file

我有一个文本文件,其中每一行包含两个“单词”,如下所示:

"(a+p(a|u)*h(a|u|i)*m)" "apehem"
"(a+p(a|u)*h(a|u|i)*a)" "correct"
"(a+p(a|u)*h(a|u|i)*e)" "correct"

第一个“单词”是一个正则表达式模式,第二个“单词”是一个实词。 两者都被双引号。

我想从上面的文件中搜索richTextBox3中每行的第一个“单词”的匹配项,并用第二个“单词”替换每个匹配项。

我尝试了这个(见下文),但是有一些错误...

System.IO.StreamReader file = new System.IO.StreamReader(@"d:\test.txt"); 

string Word1="";
string Word2="";

lineWord1 = file.ReadToEnd().Split(" ");  //Error 
string replacedWord = Regex.Replace(richTextBox3.Text, Word1, Word2, 
  RegexOptions.IgnoreCase);

richTextBox3.Text = replacedWord;

请指教。 先感谢您!

尝试一次处理一行文件。

System.IO.StreamReader file = new System.IO.StreamReader(@"d:\test.txt");

while (file.EndOfStream != true)
{
    //This will give you the two words from the line in an array
    //note that this counts on your file being perfect. You should probably check to make sure that the line you read in actually produced two words.
    string[] words = file.ReadLine().Split(' ');
    string replacedWord = Regex.Replace(richTextBox3.Text, words[0], words[1], RegexOptions.IgnoreCase);
    richTextBox3.Text = replacedWord;
}

既然您在先前的评论中提到这将是一个拼写检查器,那么我可以为您指出此链接吗? https://stackoverflow.com/a/4912071/934912

确保您的文件以unicode编码保存。

该解决方案应该为您服务>>

System.IO.StreamReader file = new System.IO.StreamReader(@"d:\test.txt");      
while (file.EndOfStream != true)      
{
  string s = file.ReadLine();
  Match m = Regex.Match(s, "\"([^\"]+)\"\\s+\"([^\"]+)\"", RegexOptions.IgnoreCase);
  if (m.Success) {
    richTextBox3.Text = Regex.Replace(richTextBox3.Text, 
      "\\b" + m.Groups[1].Value + "\\b", m.Groups[2].Value);
  }
}

我不知道您对richTextBox3的引用是什么,但是请尝试一下(未经测试,它仅是为您提供我将尝试解决的方法):

var lines = System.IO.File.ReadAllLines(@"d:\test.txt");

foreach (var line in lines)
{
    var words = line.Split(' ');
    if (words.Length > 1)
        words[0] = words[1];
}

richTextBox3.Text = string.Join(Environment.NewLine, lines);

注意将所有文件加载到内存中,因此如果文件很大,请不要这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM