1

各行に次のような2つの「単語」が含まれているテキストファイルがあります。

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

最初の「単語」は正規表現パターンであり、2番目の「単語」は実際の単語です。どちらも二重引用符で囲まれています。

richTextBox3上記のファイルから各行の最初の「単語」の一致を検索し、各一致を2番目の「単語」に置き換えたい。

これを試しましたが(以下を参照)、エラーがあります...

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;

お知らせ下さい。前もって感謝します!

4

3 に答える 3

0

ファイルを一度に1行ずつ処理してみてください。

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

于 2012-10-20T14:37:52.177 に答える
0

ファイルが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);
  }
}
于 2012-10-20T14:38:08.017 に答える
-1

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);

すべてのファイルをメモリにロードするように注意してください。ファイルが大きい場合は、これを行わないでください。

于 2012-10-20T13:31:59.493 に答える