c#用正则表达式提取json中字段的值
/// <summary>
/// 获取JSON字符串中所有指定KEY的值
/// </summary>
public static List<string> GetAllJsonValue(String jsonString, String key)
{
List<string> lst = new List<string>();
string pattern = $"\"{key}\"\\s*:\\s*\"(.*?)\\\"";
MatchCollection matches = Regex.Matches(jsonString, pattern, RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
lst.Add(match.Groups[1].Value);
}
return lst;
}
/// <summary>
/// 获取JSON字符串中首个指定KEY的值
/// </summary>
public static string GetFirstJsonValue(String jsonString, String key)
{
string pattern = $"\"{key}\"\\s*:\\s*\"(.*?)\\\"";
Match match = Regex.Match(jsonString, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
return match.Groups[1].Value;
}
return null;
}
注意,冒号: 两边的\s*,这个是匹配0次或无限次空格,有了它在格式化(PrettyPrint)后的json中也能匹配到,不然只能在压缩格式中匹配到。
参考文章:https://www.cnblogs.com/uu102/archive/2012/10/12/2721580.html
浙公网安备 33010602011771号