Skip to main content
 首页 » 编程设计

c#之正则表达式向前看或向后看

2024年02月01日26hnrainll

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

我想像这样从文本中提取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# 正则表达式获取此值吗?

请您参考如下方法:

总有一款适合你tool在这个解析 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); 
    } 
} 

一些注意事项:

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