1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

正規表現で省略するcharの分岐

Posted at

自分、訳あってコンパイラの空白文字の比較コードを書いていたらこう思いました。
これ、正規表現で省略できるぞと。
他の部分で正規表現を多用していたため気付きました。

Before

この場合は、空白かどうかを判定します。

namespace Sample{
    public class Sample{
        public static bool isEmpty(char code){
            switch(code){
                case '\t':
                case '\r':
                case '\n':
                case ' ':
                    return true;
                default:
                    return false;
            }
        }
    }
}

After

using System.Text.RegularExpressions;
namespace Sample{
    public class Sample{
        public static bool isEmpty(char code){
            return Regex.IsMatch(code.ToString(),"\\s")
        }
    }
}

説明

まず、charの引数をToStringしているため1文字なので、^\\s$のような配慮は必要ありません。
\\sは正規表現では空白の意味ですのでこれで判定可能です。

応用

これ、意外と応用できます。

  • \\dを使うことでその文字が数字かを判定する
  • [A-Z]を使うことでその文字が大文字ASCIIかを判定する
  • [ABC]を使うことでその文字がA,B,Cのどれかかを判定する
    詳細については他記事をご参照ください。
    一文字の正規表現を使えばいいですが、正規表現の\\\と書くことを注意しておいてください。
1
0
2

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?