用#替换“”之间的未知文本

时间:2013-12-13 06:27:36

标签: c# text replace

我目前有一个大文本文件,我试图用#替换“”内的任何内容之间的未知文本。我试过用:

 string text = File.ReadAllText(@"c:\Users\Zero\Documents\test.txt");
    string replacement = "#";


        int start = text.IndexOf('"') + 1;
       text = text.Replace(text.Substring(start, text.LastIndexOf('"') - start), replacement);


    File.WriteAllText(@"c:\Users\Zero\Documents\test.txt", text);

目前,它正在用一行替换文件中的所有文本。换句话说,它正在转变:

  

你好,你怎么“测试”

     

这是一个测试“123”测试

     

“测试”“测试”

  

“#”

我需要它来做这个

  

你好,你好“#”

     

这是一个测试“#”测试

     

“#”“#”

1 个答案:

答案 0 :(得分:10)

这样的regular expression会派上用场:

"[^"]*"

例如:

text = Regex.Replace(text, "\"[^\"]*\"", "\"#\"");