Regexとは
正規表現を用いて文字列の検索・置換を行うために役に立つクラスです。
正規表現に対する基本的な項目は別ページに載せていますので、そちらの方も参照してください。
使用例(文字列が当てはまるかどうか)
using System;
using System.Text.RegularExpressions;//正規表現をC#で使用する時に必要になる名前空間
class Program
{
public static void Main()
{
string[] tel = new string[] { "080-0000-0000", "06-3000-4000", "186-1123" };
string pattern = @"\d{2,4}-\d{2,4}-\d{4}";//正規表現で使用するパターン
Regex rgx = new Regex(pattern);//正規表現クラスをインスタンス化する
foreach (string hoge in tel)
{
Console.WriteLine(rgx.IsMatch(hoge)?hoge:"アンマッチ");//IsMatchメソッドで文字列比較を行う。
}
}
}
ReRexクラスはSystem.Text.RegularExpressions名前空間にあるのでusingで使用することを宣言します。
pattern文字列の宣言の前に「@」がついていますが、@の後ろの文字列リテラルは\をタグ文字ではなく普通の「\」として見てください。と言う意味です。@がなければ”\\d{2,4}-\\d{2,4}-“”d{4}”と書くことになり読みにくくなります。それを避けるために使います。
その後、Regexクラスをインスタンス化します。その際にpattern文字列を引き渡します。
後は、文字列クラスを1つずつ比較し、パターンにヒットするかどうかを判定します。
使用例(文字列を検索する)
using System;
using System.Text.RegularExpressions;
class Program
{
public static void Main()
{
string tel = "我が家の電話番号は045-123-1234です。携帯は080-1234-5678です";
string pattern = @"\d{2,4}-\d{2,4}-\d{4}";
Regex rgx = new Regex(pattern);
Match match = rgx.Match(tel);//文字列telがpatternに当てはまるかどうかを判定する
if (match.Success)
{
Console.WriteLine($"位置:{match.Index} マッチ文字列{match.Value}");
foreach(Group m in match.Groups)
{
Console.WriteLine(m.Value);
}
}
}
}
文字列telにpatternで指定した文字列に含まれるかどうかを確認します。
2つ文字列パターンに当てはまる場合は、一番最初に見つかった文字列のみを抽出します。
文字列を存在するだけ見つけ出す
using System;
using System.Text.RegularExpressions;
class Program
{
public static void Main()
{
string tel = "我が家の電話番号は045-123-1234です。携帯は080-1234-5678です";
string pattern = @"\d{2,4}-\d{2,4}-\d{4}";
Regex rgx = new Regex(pattern);
MatchCollection match = rgx.Matches(tel);//Matchesとすることで複数パターンを検索する
Console.WriteLine("マッチしたのは" + match.Count);
Console.WriteLine(match[0]);
foreach(Match m in match)//検索にヒットしたものをひとつずつ処理する
{
Console.WriteLine($"位置{m.Index}、長さ{m.Length}、マッチ文字列{m.Value}");
}
}
}
先頭の1つを見つけ出すMatchメソッドではなく、Matchesメソッドを用いることでパターンに当てはまる文字列全てを取り出します。
最長一致と最短一致
using System;
using System.Text.RegularExpressions;
class Program
{
public static void Main()
{
string str = "<p><strong>Hoge</strong>サイト<a href='index.htm></a></p>'";
string pattern = @"<.+>";
Regex rgx = new Regex(pattern);
MatchCollection match = rgx.Matches(str);
foreach(Match m in match)
{
Console.WriteLine(m.Value);
}
}
}
このプログラムを走らせると、
<p>
<strong>
</strong>
<a href='index.htm">
</a>
</p?
を期待するのですが、実際には検索対象文字列strの内容が1行で表示されます。
できるだけ長い文字列を検索するため、このような結果になっています。
そこでここのタグを取り出すべく、パターン文字列を「<+?>」のように変更します。
using System;
using System.Text.RegularExpressions;
class Program
{
public static void Main()
{
string str = "<p><strong>Hoge</strong>サイト<a href='index.htm></a></p>'";
string pattern = @"<.+?>";
Regex rgx = new Regex(pattern);
MatchCollection match = rgx.Matches(str);
foreach(Match m in match)
{
Console.WriteLine(m.Value);
}
}
}
上のように修正すると、無事に<>で囲まれた文字列が検索されました。
まとめ
正規表現における検索は様々なパターン文字列に当てはまる文字を検索し、何かの処理を加えるという強力なツールです。その為にも正規表現そのものを習得する必要があります。別ページに正規表現そのものの説明を載せていますので参照してください。
次は検索ではなく正規表現を用いた置換を取り扱います。
コメント