Skip to content

Instantly share code, notes, and snippets.

@biac
Created February 5, 2012 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biac/1741281 to your computer and use it in GitHub Desktop.
Save biac/1741281 to your computer and use it in GitHub Desktop.
.NET TIPS 正規表現を使って部分文字列を取得するには?[C#]
// 元記事 http://www.atmarkit.co.jp/fdotnet/dotnettips/579regexmatch/regexmatch.html
// その中の「HTMLからアンカー要素を抜き出すサンプル・プログラム」が残念だったので、いぢくってみる f(^^;
static void Main(string[] args) {
string anchor = "<a href=\"(?<url>.*?)\".*?>(?<text>.*?)</a>";
// @ITのトップページを取得
using (WebClient wc = new WebClient()) {
string html = wc.DownloadString("http://www.atmarkit.co.jp/");
Regex re = new Regex(anchor, RegexOptions.IgnoreCase
| RegexOptions.Singleline);
// http://www.atmarkit.co.jp/fdotnet/dotnettips/579regexmatch/regexmatch.html
// for バージョン (記事中のオリジナル)
// ※ NextMatch() を使うなら、普通 while だろうと思うのだが…。
for (Match m = re.Match(html); m.Success; m = m.NextMatch()) {
string url = m.Groups["url"].Value;
string text = m.Groups["text"].Value;
Console.WriteLine(url);
Console.WriteLine(text);
}
// Match() メソッドではなく、Matches() メソッドを使えば、
// マッチした部分の全てをコレクションとしていっぺんに取得できる。
// foreach バージョン
foreach (Match m in re.Matches(html)){
Console.WriteLine(m.Groups["url"].Value);
Console.WriteLine(m.Groups["text"].Value);
}
// LINQ Extension バージョン (Matches() が object のコレクションを返してくるのは残念)
re.Matches(html).Cast<Match>().ToList().ForEach(m => {
Console.WriteLine(m.Groups["url"].Value);
Console.WriteLine(m.Groups["text"].Value);
});
}
Console.ReadKey();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment