.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”}“

版权声明:本文为gilbert原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/gilbert/p/5316424.html