c#正则表达式捕获两个字符串之间的字符串

时间:2017-10-10 16:30:49

标签: c# html regex match

我要在角括号之间捕获一个值,我将一个'html页面解析成一个字符串(我不能使用外部库,所以我必须使用该字符串的html)。我有两个div的内容要抓,我知道他们拥有的ID,我试图通过使用正则表达式捕获内容,但我无法做到。

var div_tags = Regex.Match(json, "<div id=(.*)</div>").Groups[0];

返回我所有带有id的3 div。但我只需要两个div,其中包含“mobile”这个词。 所以..我尝试了另一个我的同事建议的正则表达式,但是如果认为它与.net正则表达式评估者不兼容。

string titolo = Regex.Replace(json, "<div id=[.*]mobile[.*]>(.*)</div>");

Thath是div的一个例子。我需要的唯一价值是消息。这两个div的id是mobileBody和mobileTitle。

<div id='mobileBody' style='display:none;'>Message</div>

我的正则表达式有什么不对,我不能抓住正确的文字?

1 个答案:

答案 0 :(得分:0)

你可以试试这个:
<[a-z\s]+id=[\'\"]mobile[\w]+[\'\"][\sa-zA-Z\d\'\=\;\:]*>([a-zA-Z\d\s]+)<[\/a-z\s]+>
无论如何它不会匹配特殊的字符或符号。
您可以在此处测试和优化它:https://regex101.com/r/fnYQ1o/10

编辑 - 代码示例
这可能是提取消息的代码部分:

 var rgx = @"<[a-z\s]+id=[\']mobile[\w]+[\'][\sa-zA-Z\d\s\'\=\;\:]*>([a-zA-Z\d\s]+)<[\/a-z\s]+>";
 var txt = "<!DOCTYPE html><html lang='it' xml:lang='it'><!-- <![endif]--><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><title>Banca Mediolanum S.p.A. | Accesso clienti</title><meta name='description' content='Banca Mediolanum S.p.A. | Accesso clienti'><meta name='keywords' content='Banca Mediolanum S.p.A. | Accesso clienti'><meta name='title' content='Banca Mediolanum S.p.A. | Accesso clienti'><meta name='author' content='Banca Mediolanum S.p.A.'><meta name='robots' content='index, follow'><meta name='viewport' content='width=1439,user-scalable=no'><link rel='shortcut icon' href='./images/favicon.ico' type='image/x-icon'><style>#cort {background-image: url(bmedonline_10set.png);background-repeat: no-repeat;background-position-x: center;height: 850px;width: auto;/*background-size: 100%;*/}@media only screen and (max-width: 768px) and (min-width: 641px) section.contactus-area.chat {}body {border: 0 none;margin: 0;padding: 0}</style></head><body class=' '><!-- Google Tag Manager --><script>(function (w, d, s, l, i) {w[l] = w[l] || [];w[l].push({'gtm.start': new Date().getTime(),event: 'gtm.js'});var f = d.getElementsByTagName(s)[0],j = d.createElement(s),dl = l != 'dataLayer' ? '&l=' + l : '';j.async = true;j.src ='//www.googletagmanager.com/gtm.js?id=' + i + dl;f.parentNode.insertBefore(j, f);})(window, document, 'script', 'dataLayer', 'GTM-KGSP');</script><!-- End Google Tag Manager --><div id='cort'></div><div id='mobileTitle' style='display:none;'>Titolo prova</div><div id='mobileBody' style='display:none;'>Corpo messaggio prova</div></body></html>";

 /* Using matches and aggregation */
 var matches = Regex.Matches(txt, rgx).Cast<Match>();
 /* Aggregation without using foreach*/
 if (matches != null && matches.Count() > 0)
 {
    matches = matches.Where(x => !String.IsNullOrEmpty(x.Groups[1].Value));
    var exitString = matches.Select(x => x.Groups[1].Value).Aggregate((x, y) => x + "-" + y);
    Console.WriteLine("Match and aggregation");
    Console.WriteLine(exitString);
  }

  /* using replace with regex: .*<div id='mobileTitle'[\s\w\W]*>([\s\w]*)<\/div>[\s\r\n]*<div id='mobileBody'[\s\w\W]*>([\s\w]*)<\/div>.* */
  Console.WriteLine();
  Console.WriteLine(@"Replace with another regex");
  Console.WriteLine(Regex.Replace(txt, @".*<div id='mobileTitle'[\s\w\W]*>([\s\w]*)<\/div>[\s\r\n]*<div id='mobileBody'[\s\w\W]*>([\s\w]*)<\/div>.*", "$1-$2"));

  Console.ReadLine();