LoginSignup
2
1

More than 3 years have passed since last update.

[C#]正規表現で、ルールに一致した文字列かどうか調べる/一致した文字列を抜き出す

Posted at

やりたいこと

特定のルールに合致した文字列であるかどうかを確認したい。
また、ルールに合致した文字列を抜き出したい。

やり方

Regexクラスを使う。

サンプルコード

using System;
using System.Text.RegularExpressions;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            string org = "1dg4-fasd-kf5g-fsaa";

            // ①4桁の英数字を-でつなげたものかどうかを判定
            if (Regex.IsMatch(org, @"^[\da-zA-Z]{4}-[\da-zA-Z]{4}-[\da-zA-Z]{4}-[\da-zA-Z]{4}\z"))
            {
                Console.WriteLine("マッチしました!");
            }

            // ②4桁英数字にマッチしたものを探す
            var match = Regex.Match(org, @"[\da-zA-Z]{4}");
            Console.WriteLine("1個だけ探す:" + match.Value);

            // ③4桁英数字にマッチしたものを全部探す
            var matches = Regex.Matches(org, @"[\da-zA-Z]{4}");
            foreach (Match m in matches)
            {
                Console.WriteLine("全部探す:" + m.Value);
            }
        }
    }
}

こうなる
image.png

参照

.NET の正規表現
https://docs.microsoft.com/ja-jp/dotnet/standard/base-types/regular-expressions

【C#入門】正規表現の使い方総まとめ(Match/Matches/Replace)
https://www.sejuku.net/blog/54508

【C#】正規表現の使い方
https://qiita.com/github129/items/5a2cd4d36abdf4ebe870

サルにもわかる正規表現
https://www.mnet.ne.jp/~nakama/

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1