[英]Regex lookahead or lookbehind
我正在學習如何使用正則表達式向前和向后看。
我想像這樣從文本中提取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#正則表達式獲得此值嗎?
在解析JSON對象的情況下, 正是您需要的一個完美工具 。
好吧,如果您正在學習正則表達式,這是檢索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);
}
}
一些注意事項:
(?<!\\\\)
作為(從此處開始 )的負向后看。 RegexOptions.Singleline
作為點( .
)字符以匹配換行符(\\ r&\\ n)。 /"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
在這種情況下應該是足夠好的近似值。
(我已經以標准的regexp方式編寫了它;請記住對C#字符串文字使用反斜杠和引號。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.