Created
February 5, 2012 00:05
-
-
Save biac/1741281 to your computer and use it in GitHub Desktop.
.NET TIPS 正規表現を使って部分文字列を取得するには?[C#]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 元記事 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