C#
パターン4:全角半角判定— Unicode範囲
出典: C# 正規表現の業務系基本 — メール / 電話 / 郵便番号 / 全角半角の入力検証5パターン — パターン4:全角半角判定— Unicode範囲
using System.Text.RegularExpressions;
public static class CharTypeValidator
{
// ✅全角文字(ASCII外)が含まれているか
private static readonly Regex FullWidthRegex = new Regex(
@"[^\x00-\x7F]",
RegexOptions.Compiled);
// ✅半角カナが含まれているか
private static readonly Regex HalfWidthKanaRegex = new Regex(
@"[。-゚]",
RegexOptions.Compiled);
// ✅日本語文字(ひらがな・カタカナ・漢字)のみ
private static readonly Regex JapaneseOnlyRegex = new Regex(
@"^[ぁ-んァ-ヶ一-龯]+$",
RegexOptions.Compiled);
public static bool ContainsFullWidth(string input)
{
if (string.IsNullOrEmpty(input))return false;
return FullWidthRegex.IsMatch(input);
}
public static bool ContainsHalfWidthKana(string input)
{
if (string.IsNullOrEmpty(input))return false;
return HalfWidthKanaRegex.IsMatch(input);
}
public static bool IsJapaneseOnly(string input)
{
if (string.IsNullOrEmpty(input))return false;
return JapaneseOnlyRegex.IsMatch(input);
}
}
//使い方
class Program
{
static void Main()
{
Console.WriteLine(CharTypeValidator.ContainsFullWidth("abc")); // False
Console.WriteLine(CharTypeValidator.ContainsFullWidth("abc日本語")); // True
Console.WriteLine(CharTypeValidator.ContainsFullWidth("ABCあ")); // True (全角A)
Console.WriteLine(CharTypeValidator.ContainsHalfWidthKana("アイウ")); // True
Console.WriteLine(CharTypeValidator.IsJapaneseOnly("こんにちは")); // True
Console.WriteLine(CharTypeValidator.IsJapaneseOnly("Hello")); // False
}
}
▸ 実行ボタンで結果を表示
Source収録記事
この snippet は記事の「パターン4:全角半角判定— Unicode範囲」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
5 件using System.Text.RegularExpressions; public static class EmailValidator {
▶ 実行可
パターン1:メールアドレス検証—簡易版が現実解
#8e620c411684
using System.Text.RegularExpressions; public static class PhoneValidator {
▶ 実行可
パターン2:電話番号検証—国内+国際対応
#f2eebc57a171
using System.Text.RegularExpressions; public static class PostalCodeValidator {
▶ 実行可
パターン3:郵便番号検証— 7桁ハイフン形式
#da3fce3a8fab
using System; using System.Text.RegularExpressions; public static class FormatValidator
▶ 実行可
パターン5:数値・日付フォーマット検証
#5f14a216eab8
using System.Diagnostics; using System.Text.RegularExpressions; public static class RegexPerformanceComparison
▶ 実行可
パターン6: RegexOptions.Compiledでパフォーマンス改善
#228fa557c142
