日期:2014-05-20  浏览次数:20773 次

提问,还是Regex类的东东 ,请问怎么用它来替换字符串,???Regex.Replace...
是这样的
字符串:
  string   str   =   "packet   size=4096;user   id=sa;data   source=ddd;persist   security   info=True;initial   catalog=plan;password=aaa ";

现在有一个新的,用户名是   sasas
密码是       abcde

现在俺的目的就是将   新的用户名   sasas,和密码   abede   ,来替换上面字符串中的相应的字符串

替换后变成
"packet   size=4096;user   id=sasas;data   source=ddd;persist   security   info=True;initial   catalog=plan;password=abede ";



------解决方案--------------------
try..

string str = "packet size=4096;user id=sa;data source=ddd;persist security info=True;initial catalog=plan;password=aaa ";
Regex rx = new Regex(@ "user id=(\w+);.*password=(\w*)[;]? ");
Match m=rx.Match (str );
string s=m .Groups [0].Value ;
string username = m.Groups[1].Value;
string pwd = m.Groups[2].Value;
string result = s.Replace(username, "sasas ");
result = result.Replace(pwd, "abede ");
str = str.Replace(s, result);
Console.WriteLine(str);

------解决方案--------------------
试下下面的,应该更具有灵活性吧

string yourStr = "packet size=4096;user id=sa;data source=ddd;persist security info=True;initial catalog=plan;password=aaa ";
string id= "sasas ";
string password= "abcde ";
string resultStr = Regex.Replace(yourStr, "((.*?)user id=)(.*?)(;(.*?)password=)(.*) ", "$1 "+id+ "$4 "+password,RegexOptions.IgnoreCase);
Console.Write(resultStr);