C#で正規表現を使う (IsMatch/Match)
正規表現のテストに便利なサイト
- Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript
- Rubular: a Ruby regular expression editor
IsMatch
string strTarget = @"本日は閉店なり";
if(Regex.IsMatch(strTarget, @"(.+?)は(.+?)なり$"))
{
Console.WriteLine("IsMatch : Match!!");
}
IsMatch : Match!!
Match
string strTarget = @"本日は閉店なり";
Match objMatch = Regex.Match(strTarget, @"(.+?)は(.+?)なり$");
if (objMatch.Success)
{
Console.WriteLine("Groups[1] : " + objMatch.Groups[1].Value);
Console.WriteLine("Groups[2] : " + objMatch.Groups[2].Value);
}
Groups[1] : 本日
Groups[2] : 閉店
Match (グループ名指定)
string strTarget = @"本日は閉店なり";
Match objMatchGroup = Regex.Match(strTarget, @"(?<day>.+?)は(?<action>.+?)なり$");
if (objMatchGroup.Success)
{
Console.WriteLine("Groups[day] : " + objMatchGroup.Groups["day"].Value);
Console.WriteLine("Groups[action] : " + objMatchGroup.Groups["action"].Value);
}
Groups[day] : 本日
Groups[action] : 閉店
複数件マッチさせる場合
string strTarget = @"本日は閉店なり。明日は開店なり。";
Match objMatchGroup = Regex.Match(strTarget, @"(?<day>.+?)は(?<action>.+?)なり。");
while (objMatchGroup.Success) {
Console.WriteLine("Groups[day] : " + objMatchGroup.Groups["day"].Value);
Console.WriteLine("Groups[action] : " + objMatchGroup.Groups["action"].Value);
objMatchGroup = objMatchGroup.NextMatch();
}
Groups[day] : 本日
Groups[action] : 閉店
Groups[day] : 明日
Groups[action] : 開店
ディスカッション
コメント一覧
まだ、コメントがありません