我想我已經寫了什麼,我想在標題做,所以現在給點意見:返回唯一真正的一個
- 我有一個網址.txt文件鏈接及其源代碼將被正則表達式解析。每一個環節的
的源代碼是由該刮:
public static string getSourceCode(string url) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); StreamReader sr = new StreamReader(resp.GetResponseStream()); string sourceCode = sr.ReadToEnd(); sr.Close(); resp.Close(); return sourceCode; }
每個源代碼包含以下內容:
..code..
..code..
<p class="content">
exampleexampleexample
</p>
..code..
..code..
<p class="content">
example
</p>
..code..
..code..
有content
元素更多的元素。
- 我得到
content
內容由這樣的:
Regex k = new Regex(@"<p class=""question-content"">[\r\n\s]*(\S.*)"); var g = k.Matches(sourceCode);
現在我可以伊斯利提取每場比賽:
g[1].ToString() <-- first match
g[2].ToString() <-- second match
g[3].ToString() <-- thirdmatch
等
但我想要做的是提取這些鏈接:首場比賽不包含XYZ
,但至少在其他比賽中有XYZ
。
例如:
首先鏈接的源代碼包含XYZ
在第一和第三場比賽< - 錯
第二個鏈接的源代碼包含XYZ
只在第一場比賽< - 錯
第三個鏈接的源代碼僅包含XYZ
第三個匹配< - 成功!
解決方案
我從中得到每場比賽總彙:
MatchCollection b1 = Regex.Matches(sourceCode, @"<p class=""content"">[\r\n\s]*(\S.*)");
我要做的未來是 檢查,如果第一場比賽中不包含 「榜樣」 這個:
if (!b1[0].ToString().Contains("example"))
並檢查此功能的結果:
bool checkAnother(int amount, MatchCollection m)
{
for (int i=1; i<=amount-1; i++)
{
if (m[i].ToString().Contains("example"))
return true;
}
return false;
}
所以這是代碼:
MatchCollection b1 = Regex.Matches(sourceCode, @"<p class=""content"">[\r\n\s]*(\S.*)");
if ((!b1[0].ToString().Contains("example")) && (checkAnother(b1.Count, b1)))
{dataGridView1.Rows[i].Cells[2].Value = "GOOD";
}
是使用正則表達式這樣的硬性要求,或者乾脆你的方法目前在嘗試?此外,目前的問題是什麼?我可以看到你沒有任何真正終止你的正則表達式的東西,但否則它看起來像是一組簡單的if/else語句。 –
我在那裏使用正則表達式,因爲我的編程技巧不夠好(atm),以便更好地解決我的需求。 – audiophonic
我建議使用像[CsQuery](https://github.com/jamietre/CsQuery)這樣的DOM walker(雖然這個人肯定不再維護),而不是正則表達式來處理XML/HTML風格的語言。儘管如此,你並不完全清楚你所擁有的_problem_是什麼。 –