【问题标题】:removing # from the words in c# using Regex使用正则表达式从 c# 中的单词中删除 #
【发布时间】:2013-03-02 12:26:07
【问题描述】:

我想读取带有“#”附加到单词的文件我想从单词中删除它
输入文件

a, 00001740, 0.125, 0,     able#1
a, 00001740, 0.125, 0,     play#2
a, 00002098, 0,     0.75,  unable#1

我想要以下没有#
输出应该是这样的格式

a, 00001740, 0.125,  0,      able
a, 00001740, 0 .125, 0,      play
a, 00002098, 0,      0.75,   unable

我写如下代码

TextWriter tw = new StreamWriter("D:\\output.txt");
private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "")
            {

                StreamReader reader = new StreamReader("D:\\input.txt"); 
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    Regex expression = new Regex(@"\b\w+(?=#\d*\b)");
                    var results = expression.Matches(reader.ToString())
                    foreach (Match match in results)
                    {


                        tw.Write(match);

                    }
                    tw.Write("\r\n");
                }
                tw.Close();
                reader.Close();
            }
            textBox1.Text = "";                    
        }
    }

【问题讨论】:

  • 也许您可以替换 # 并删除尾随数字..

标签: c# regex c#-4.0


【解决方案1】:

使用Regex.Replace()

string result = Regex.Replace(input, "#.*", "");

【讨论】:

    【解决方案2】:

    如果您不想读取和缓存文件的全部内容,您可能希望将其写入其他文件,因为您在读取原始文件的内容时正在重写文件。

    另外,考虑这个例子:

    int index = line.IndexOf("#");
    if (index != -1)
    {
        line = line.Substring(0, index - 1);
    }
    

    在这里您不必处理正则表达式,因此运行速度会更快。

    【讨论】:

      【解决方案3】:

      您的整个代码可以替换为 3 行:

      string txt = File.ReadAllText("D:\\input.txt");
      txt = Regex.Replace(txt, "#.*?(\r\n|\n|$)", "$1");
      File.WriteAllText("D:\\output.txt", txt);
      

      【讨论】:

        【解决方案4】:

        正则表达式替换可能是最好的选择。

         File.WriteAllLines("c:\\output.txt", File.ReadAllLines("c:\\input.txt").Select(line => Regex.Replace(line, "#.*","")));
        

        或者可能是TakeWhile

        File.WriteAllLines("c:\\test24.txt", File.ReadAllLines("c:\\test.txt").Select(line => new string(line.TakeWhile(c => c != '#').ToArray())));
        

        【讨论】:

          【解决方案5】:

          按照我的评论试试这个:

                  string s = "a, 00001740, 0.125, 0,     able#1";
                  string m = Regex.Replace(s, @"#\d$", ""); 
                  //for more than one digit  @"#\d+$"
                  Console.WriteLine(m);
                  Console.ReadLine();
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-08-07
            • 2014-06-21
            • 1970-01-01
            • 1970-01-01
            • 2023-03-05
            • 1970-01-01
            • 2020-01-25
            • 1970-01-01
            相关资源
            最近更新 更多