正则表达式-替换文本文件中一行的一部分 [英] Regular Expressions-replacing part of a line in text file

查看:146
本文介绍了正则表达式-替换文本文件中一行的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

我需要在文本文件中编辑特定行的一部分.

我要编辑的文本文件中的行是:
登录=''.登录用户名密码\ r \ n''

我想用在表单文本框中输入的用户名和密码替换用户名和密码.

文本文件中上一行中的当前用户名和密码字段可以是任何内容.

在不确切知道当前用户名和密码是什么的情况下,如何用表单文本框用户名和密码字符串替换上面的行?

我使用了下面的代码,但这仅替换了我指定的字符串,并且我知道:(

Hi Guys

I need to edit part of a specific line in a text file.

The line in the text file I want to edit is:
login = ''. login username password\r\n''

I want to replace the username and password with the ones entered in my form text boxes.

The current username and password fields in the above line in the text file could be anything.

How can I replace the above line with my form textbox username and password strings without knowing exactly what the current username and password are??

I have used the code below but this only replaces strings that I specify and that I know :(

public static bool Replace(ref string file, ref string searchFor, ref string replaceWith)
        {
            try
            {   
                StreamReader reader = new StreamReader(file);
                string contents = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();
                contents = Regex.Replace(contents, searchFor, replaceWith);
                StreamWriter writer = new StreamWriter(file);
                writer.Write(contents);
                writer.Close();
                writer.Dispose();
                return true;
            }

任何帮助将不胜感激.非常感谢!

any help would be appreciated. Many thanks!

推荐答案

萨克!

如果您感兴趣的行以"login ="
开头 我只是搜索它,当发现它时,写出
新组装线:
String accountInfo = "login=" + login + " " + password.那应该可以解决问题.



现在我知道了:

Hi Sach!

if the line you''re interested in starts with "login = "
I''d just search for that and when it''s found write out the
newly assembled line:
String accountInfo = "login=" + login + " " + password. That should do the trick.



Now I''ve got it:

searchFor = "(\\s+login\\s*=\\s*)(.+)(\\r\\n)";
replaceWith = "


1" + userName + " " + password + "
1" + userName + " " + password + "


3"); contents = "# This is a test\r\n" + "login = Will be replaced\r\n" + "# more test lines\r\n" + "login2 = Wont be touched\r\n" "# more test\r\n";
3"); contents = "# This is a test\r\n" + "login = Will be replaced\r\n" + "# more test lines\r\n" + "login2 = Wont be touched\r\n" "# more test\r\n";





The


这篇关于正则表达式-替换文本文件中一行的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆