[英]Match Collection Regex Pattern
我正在尝试找出正则表达式模式,以从我的正文中获取“ displayName”和“ id”。 (一个json对象)。
来源如下:
"value": [
{
"displayName": "Alpha,Patient",
"id": "0-50F!16077"
},
{
"displayName": "Beta,Patient",
"id": "0-50F!16078"
},
{
"displayName": "Beta6,Pateint",
"id": "0-50F!12035"
},
{
"displayName": "Delta,Patient",
"id": "0-50F!16399"
},
这是我正在使用的Regex模式和代码。
string regularExpressionPattern1 = "\\{(.*?)\\},";
Regex regex = new Regex(regularExpressionPattern1, RegexOptions.Singleline);
MatchCollection collection = regex.Matches(body.ToString());
string tempStr=collection[0].Groups[1].ToString();
foreach(Match m in collection)
{
string[] tempArray = m.Value.ToString().Split(',');
}
逃避花括号是我能想到的最好的选择。
我希望我的收藏看起来像:
Alpha,患者,0-50FCF5!16077 Beta,患者,0-50FCF5!16077
它不是很漂亮,但是如果您必须使用正则表达式,并且可以确定文本是什么样的:
var re = new Regex(@"(?s)displayName"": ""(?<name>.+?)"",.*?id"": ""(?<id>.+?)""");
foreach (Match match in re.Matches(text))
{
Console.WriteLine($"displayName = {match.Groups["name"]} | id = {match.Groups["id"]}");
}
// displayName = Alpha,Patient | id = 0-50F!16077
// displayName = Beta,Patient | id = 0-50F!16078
// displayName = Beta6,Pateint | id = 0-50F!12035
// displayName = Delta,Patient | id = 0-50F!16399
但是,实际上,如果您的文本是JSON,那么正确的JSON解析器可能会给您更令人满意的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.