我正在学习如何使用正则表达式前瞻和后视。
我想像这样从文本中提取 json 值
{"html":"ntttt<table class="table">"}
我在 C# 上使用正则表达式,如下所示
Regex.Match(text, ""html":"([^(?<!\\)"]*)").Groups[1].Value
或
Regex.Match(text, ""html":"((?<!\\$)[^"]*)").Groups[1].Value
但它根本不起作用。我可以使用 C# 正则表达式获取此值吗?
有一个完全完美的工具,正是您在解析 JSON 对象的情况下所需要的。
好的,如果您正在学习正则表达式,以下是检索 JSON 数据的示例:
class Program
{
static void Main(string[] args)
{
// {"html":"ntttt<table class="table">"}
var s = "{"html":"ntttt<table class=\"table\">"}";
Console.WriteLine(""{0}"", ParseJson("html", s).First());
// You might wanna do Trim() on the string because of those ttt 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);
}
}
一些注意事项:
- 使用
(?<!\)
作为前面没有反斜杠的双引号的负回溯(从这里开始)。 - 对点 (
.
) 字符使用RegexOptions.Singleline
以匹配换行符 (\r & )。 - 不要使用正则表达式:)解析 HTML
/"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# 字符串文本的反斜杠和引号进行转义。