&tag(CSharp/正規表現); *目次 [#teeaa52f] #contents *参考情報 [#k74c4cd2] -[[正規表現の基本: .NET Tips: C#, VB.NET, Visual Studio:http://dobon.net/vb/dotnet/string/regex.html]] -[[正規表現の基本 - Programming/.NET Framework/正規表現 - 総武ソフトウェア推進所:http://smdn.jp/programming/netfx/regex/0_abstract/]] *基本 [#n45d9b19] -Regexクラスのメソッドを使う。 -インスタンスメソッドとstaticメソッド両方あるが、同じ正規表現を使い回す場合はインスタンスメソッドを使うという方針でよさそう。 ,メソッド名,目的,戻り値 ,IsMatch,正規表現と一致するかどうかを判定。,bool ,Match,最初のマッチだけ取得。,Match ,Matches,全てのマッチを取得。,MatchCollection ,Split,正規表現で文字列を分割,stringの配列 ,Replace,マッチする箇所を置換,string -@マークを使って文字列中の\をエスケープシーケンスとして解釈させないことができる( つまり、@"\d"などとかくことができる)ので複雑な正規表現を書く場合便利。 *正規表現要素 [#h12025c6] -正確には[[正規表現言語要素:http://msdn.microsoft.com/ja-jp/library/az24scfc.aspx]]を参照のこと。 -個人的によく使う正規表現。 ,サンプル,意味 ,[a-z0-9],aからzと0から9にマッチ。 ,.,任意の1文字。 ,*,直前の文字の0文字異常の繰り返し。 ,(a+),aの繰り返しをグループとしてキャプチャ。 ,^,文字列の先頭にマッチ。 ,$,文字列の末尾にマッチ。 ,\s,空白にマッチ。 ,\S,空白以外にマッチ。 ,\d,数字にマッチ。 *IsMatch [#i96da58e] -正規表現が一致するかどかを判定するだけのメソッド。一致した部分を後から操作とかはできない。 -サンプル。 #pre{{ string str = "Hello world!"; Regex reg = new Regex(@"world"); if (reg.IsMatch(str)) { Debug.WriteLine("Match"); } else { Debug.WriteLine("Not Match"); } }} -出力。 Match *Match [#de22f82f] -正規表現の最初の一致をMatchとして返す。一致したかどうかはMatchクラスのSuccessプロパティで判定できる。一致した部分文字列はMatchクラスのGroupsプロパティから取得できる。 -サンプル。 #pre{{ string str = "Hello woooooorld!"; Regex reg = new Regex(@"w(o+)rld"); Match m = reg.Match(str); if (m.Success) { Debug.WriteLine("Match"); Debug.WriteLine("Groups[0]=" + m.Groups[0].Value); Debug.WriteLine("Groups[1]=" + m.Groups[1].Value); } else { Debug.WriteLine("Not Match"); } }} -出力。 #pre{{ Match Groups[0]=woooooorld Groups[1]=oooooo }}