我正在学习如何使用正则表达式前瞻和后瞻。
我想从文本中提取json值,就像这样
{"html":"\n\t\t\t\t<table class=\"table\">"}
我正在使用C#这样的正则表达式
Regex.Match(text, "\"html\":\"([^(?<!\\\\)\"]*)").Groups[1].Value
或
Regex.Match(text, "\"html\":\"((?<!\\\\$)[^\"]*)").Groups[1].Value
但它根本不起作用。我可以使用C#regex获得此值吗?
答案 0 :(得分:4)
对于tool来说,完全非常适合完全在解析JSON对象时需要的内容。
好的,如果你正在学习Regex,这是你检索JSON数据的例子:
class Program
{
static void Main(string[] args)
{
// {"html":"\n\t\t\t\t<table class=\"table\">"}
var s = "{\"html\":\"\n\t\t\t\t<table class=\\\"table\\\">\"}";
Console.WriteLine("\"{0}\"", ParseJson("html", s).First());
// You might wanna do Trim() on the string because of those \t\t\t etc.
}
static private IEnumerable<string> ParseJson(string key, string input)
{
Regex r = new Regex(@"\{\""" + key + "\""\:\""(.*?)(?<!\\)\""\}", RegexOptions.Singleline);
return r.Matches(input).Cast<Match>().Select(T => T.Groups[1].Value);
}
}
一些注意事项:
(?<!\\)
作为负面观察(来自here),而双引号前面没有反斜杠。RegexOptions.Singleline
作为点(.
)字符以匹配换行符(\ r&amp; \ n)。答案 1 :(得分:1)
/"html":"(?:[^"]*(\\"[^"]*(?<!\\)))*"/
- opening quote
----- ----- - then any number of non-quotes
---- - ... separated by an escaped quote
------- ... where the non-quote string doesn't
end in a backslash
- closing quote
对于这种情况,应该是一个足够好的近似值。
(我用标准的正则表达式编写它;记得为C#字符串文字转义反斜杠和引号。)