正则表达式向前看或向后看

时间:2013-11-15 19:06:49

标签: c# regex

我正在学习如何使用正则表达式前瞻和后瞻。

我想从文本中提取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获得此值吗?

2 个答案:

答案 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);
    }
}

一些注意事项:

  1. 使用(?<!\\)作为负面观察(来自here),而双引号前面没有反斜杠。
  2. 使用RegexOptions.Singleline作为点(.)字符以匹配换行符(\ r&amp; \ n)。
  3. Do not parse HTML with regex:)

答案 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#字符串文字转义反斜杠和引号。)