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

Posted 陈哲Gilbert

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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"}“

以上是关于C#中,使用正式表达式匹配获取所需数据的主要内容,如果未能解决你的问题,请参考以下文章