我编写了一个程序,将文本文件读入变量,在文本上替换正则表达式,并将其写回文件.显然,这不适用于大型文本文件;我希望能够逐行读取文本文件并为所需模式执行正则表达式替换.
这是我的不可扩展代码:
static void Main(string[] args) { var fileContents = System.IO.File.ReadAllText("names.txt"); string pattern = "Ali"; string rep = "Tyson"; Regex rgx = new Regex(pattern); fileContents = rgx.Replace(fileContents,rep); System.IO.File.WriteallText("names.txt",fileContents);}
我知道如何使用StreamReader逐行读取文件,但是当我在StreamReader中尝试嵌套StreamWriter时,我可以在逐行搜索时写入文件,我遇到了未处理的异常错误.
有谁知道如何解决这个问题?
解决方法
你可以试试这个,
using (var input = File.OpenText("input.txt")) using (var output = new StreamWriter("output.txt")) { string line; while (null != (line = input.ReadLine()) { // Apply regex to line before writing to new outpu file output.WriteLine(line); } }
一旦读完并将所有行写入output.txt,就可以用output.txt替换input.txt.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。