【问题标题】:c# How to proceed replacements based on regex patterns from the filec#如何根据文件中的正则表达式模式进行替换
【发布时间】:2012-10-21 02:50:46
【问题描述】:

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

"(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;

请指教。提前谢谢!

【问题讨论】:

    标签: c# regex split text-files


    【解决方案1】:

    确保您的文件使用 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);
      }
    }
    

    【讨论】:

      【解决方案2】:

      尝试一次处理一行文件。

      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

      【讨论】:

        【解决方案3】:

        我不知道你对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);
        

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

        【讨论】:

        • 我猜我的文件会超过 500MB。并且必须使用正则表达式,因为第一个单词实际上是正则表达式。
        猜你喜欢
        • 2012-02-12
        • 1970-01-01
        • 1970-01-01
        • 2016-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-29
        • 1970-01-01
        相关资源
        最近更新 更多