2017-10-10 3 views
-8

대괄호 값을 catch해야했습니다. an'html 페이지를 문자열로 구문 분석합니다 (외부 라이브러리를 사용할 수 없으므로 문자열과 같은 HTML을 사용해야합니다) . 두 div의 콘텐츠를 잡을, 나는 그들이 가진 id 알고 정규식을 사용하여 콘텐츠를 잡으려고 해요,하지만 그것을 할 수 없습니다. 나에게 내가 ID로 모두 3 개의 사업부를 반환두 문자열 사이의 Regex catch 문자열

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

. 하지만 나는 두 개의 div 만 필요합니다. id에는 "mobile"이라는 단어가 들어 있습니다. 그래서 .. 내 동료가 제안한 또 다른 정규식을 시도했지만, 그것이 .net regex evaluationetor와 호환되지 않는다고 생각한다면. 사업부의 예 Thath

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

. 내가 필요한 유일한 가치는 메시지 야. 두 div의 id는 mobileBody 및 mobileTitle입니다. 내가 올바른 텍스트를 잡을 수 없습니다 내 정규식 잘못 무엇

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

?

+3

사용과 같은 HTML 파서를 [HtmlAgilityPack] (http://html-agility-pack.net/?z=codeplex). 또한 https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags –

+3

을 참조하십시오. HTML 파서를 사용해야합니다. – SLaks

+0

나는 외부 라이브러리를 사용할 수 없기 때문에 HtmlAgilityPack을 사용할 수 없다고 말했습니다. –

답변

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(); 
+0

안녕하십니까, 답장을 보내 주셔서 감사합니다. 나는 방법을 사용하기 전에 : Regex.Match (string, "your_regex"); "인식 할 수없는 이스케이프 시퀀스"오류가 있습니다. 내가 정규식 앞에 @를 배치하면 오류도 발생합니다. 어떻게 오류를 제거 할 수 있습니까? –