うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】正規表現に対応した TextField

TextField で入力制限をしたかったので作成、入力のたびに判定したかったがうまく行かなかったのでDelayedTextField を利用している

using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
 
public static class EditorGUIExtension
{
    public static string RegexTextField(string label, string value, string regex)
    {
        using (var check = new EditorGUI.ChangeCheckScope())
        {
            var t = EditorGUILayout.DelayedTextField(label, value);
            if (check.changed)
            {
                var builder = new StringBuilder();
                foreach (Match m in Regex.Matches(t, regex))
                    builder.Append(m.Value);
 
                return builder.ToString();
            }
        }
 
        return value;
    }
}

サンプル

// 数値だけがほしい場合
num = EditorGUIExtension.RegexTextField("Number Only", num, "([0-9])*");
 
// アルファベットのみ
text = EditorGUIExtension.RegexTextField("Alphabet Only", text, "([a-z]|[A-Z])*");
 
// 数字と.のみ
Version = EditorGUIExtension.RegexTextField("Version", Version, "([0-9]|\\.)*");