C#中,使用正则表达式匹配获取所需数据


.NET中,使用正则表达式匹配获取所需数据

 

需求:获取一串字符串中,正则匹配出需要的数据。

例如以下字符串:

string temp ="ErrorCode:-1,Message:{"UserId" : "1000","userName" : "ZhangSan"}";

我需要获得“-1”和“{"UserId" : "1000","userName" : "ZhangSan"}”;

 

接下来,就使用正则去匹配:

using System.Text.RegularExpressions;

string temp = "ErrorCode:-1,Message:{\"UserId\" : \"1000\",\"userName\" : \"ZhangSan\"}";
Regex reg = new Regex("ErrorCode:(?<key1>.*?),Message:{(?<key2>.*?)}");
Match match = reg.Match(temp);
string tempStr = match.Groups["key1"].Value + "--" + match.Groups["key2"].Value;

MessageBox.Show(tempStr);

 

 

这时候tempStr得到的是”-1--{"UserId" : "1000","userName" : "ZhangSan"}“


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM