C#にてGUIアプリケーションを作成するときに使用する
TextBox などで入力文字の制限をする場合に使用する。特定文(整数値、実数値、金額、住所)に含まれる文字かを判断する方法を説明します。
特定文に含まれる文字かを判断
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
// 半角数字か判断する static public bool IsHalfNumeric(char c) { if (c >= '0' && c <= '9') { return true; } return false; } // 半角整数値か判断する static public bool IsHalfDigit(char c) { if ((c >= '0' && c <= '9') || c == '-' || c == '+') { return true; } return false; } // 半角実数値か判断する static public bool IsHalfReal(char c) { if ((c >= '0' && c <= '9') || c == '-' || c == '+' || c == '.') { return true; } return false; } // 半角16進数か判断する static public bool IsHalfHex(char c) { if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) { return true; } return false; } // 半角英文字か判断する static public bool IsHalfAlpha(char c) { if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) { return true; } return false; } // 半角英数字か判断する static public bool IsHalfAlnum(char c) { if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) { return true; } return false; } // 半角カナ文字か判断する static public bool IsHalfKana(char c) { if (c >= 'ア' && c <= 'ン') { return true; } return false; } // 半角表示文字か判断する static public bool IsHalfDisplay(char c) { if ((c >= ' ' && c <= '~') || (c >= '。' && c <= '゚')) { return true; } return false; } // 半角日付文字か判断する static public bool IsHalfDate(char c) { if ((c >= '0' && c <= '9') || c == '/') { return true; } return false; } // 半角時間文字か判断する static public bool IsHalfTime(char c) { if ((c >= '0' && c <= '9') || c == ':') { return true; } return false; } // 半角電話番号文字か判断する static public bool IsHalfPhone(char c) { if ((c >= '0' && c <= '9') || c == '-') { return true; } return false; } // 半角郵便番号文字か判断する static public bool IsHalfPost(char c) { if ((c >= '0' && c <= '9') || c == '-') { return true; } return false; } // 全角カナ文字か判断する static public bool IsDblKatakana(char c) { Regex regex = new Regex("^[ァ-ヴ!ー]+$"); if (!regex.IsMatch(c.ToString())) { return false; } return true; } // 全角かな文字か判断する static public bool IsDblHiragana(char c) { Regex regex = new Regex("^[ぁ-ん!ー]+$"); if (!regex.IsMatch(c.ToString())) { return false; } return true; } |
単純なものはif文にて行なえますが、複雑になるとif文ではプログラムが複雑になります。
そこで上記の例では、正規表現にて行っています。
全て正規表現にて行なうことも出来ます。速度など考慮の上ご自分で判断してください。