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