F#で正規表現を使って日本語をマッチさせる

まずひらがな。

Regex.IsMatch("あ", "\p{IsHiragana}") // => true

F# では .NetRegex クラスによって正規表現を扱う。Unicodeのコードポイントの範囲ごとに IsHiragana のような名前が付けられており、その名前を \p{IsHiragana} のように指定することができる。

使用可能な名前一覧は .NET 正規表現での文字クラス | Microsoft Learn を参照。これによると IsHiragana は 3040 ~ 309F と書いてあるが、Wikipedia にあるコード一覧を見ると確かにひらがなはこの範囲にありそうである。

続いてカタカナ、漢字。 IsCJKUnifiedIdeographs は日本語ではCJK統合漢字と呼ぶらしい。

Regex.IsMatch("ア", "\p{IsKatakana}")
Regex.IsMatch("亜", "\p{IsCJKUnifiedIdeographs}")

最後に、全角記号、全角数字、半角カタカナ。

Regex.IsMatch("、", "\p{IsCJKSymbolsandPunctuation}")
Regex.IsMatch("「", "\p{IsCJKSymbolsandPunctuation}")
Regex.IsMatch(">", "\p{IsHalfwidthandFullwidthForms}")
Regex.IsMatch("1", "\p{IsHalfwidthandFullwidthForms}")
Regex.IsMatch("ア", "\p{IsHalfwidthandFullwidthForms}")

全角記号に関しては IsCJKSymbolsandPunctuation にあったり IsHalfwidthandFullwidthForms にあったりして分け方がよくわからないが、両方入れておけばよさそうではある。

Regex.IsMatch("、", "\p{IsCJKSymbolsandPunctuation}|\p{IsHalfwidthandFullwidthForms}")
Regex.IsMatch(">", "\p{IsCJKSymbolsandPunctuation}|\p{IsHalfwidthandFullwidthForms}")