動くコード図鑑技術記事現場の渡り方キャリア論すべての記事About
C#

パターン4:全角半角判定— Unicode範囲

出典: C# 正規表現の業務系基本 — メール / 電話 / 郵便番号 / 全角半角の入力検証5パターンパターン4:全角半角判定— Unicode範囲

パターン4:全角半角判定— Unicode範囲 (csharp)#50a671243a77
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
    }
}
▸ 実行ボタンで結果を表示
  • id: #50a671243a77
  • lines: 52
  • extracted: 2026-06-10
  • captured: 2026-06-04

Source収録記事

この snippet は記事の「パターン4:全角半角判定— Unicode範囲」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。

同じ記事から

5
図鑑トップ