1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【正規表現】全角文字をチェックしたい

Posted at

はじめに

バリデーションチェックを実装中に全角文字を判定する方法がわからなかったため、調べたことをまとめます。

問題

外部サービスのIFからの入力値の項目で全角文字かどうかを判定したい。

解決方法

正規表現を使用する

正規表現の^[^ -~。-゚]+$を使用して実現できました。

半角英数字記号、半角カタカナ以外=全角文字で判定

パターンの構成

  • ^:入力の先頭を表す
  • $:入力の末尾を表す
  • []:文字クラス
  • [^ ]:否定文字クラス
  • -~:半角スペースからチルダを表す=文字コードで半角英数字記号全てが対象
  • 。-゚:半角句点から半角半濁点を表す=文字コードの半角カタカナすべてが対象
const target: string = "全角文字";
// const target: string = "12345"

if(target != null && target.match("^[^ -~。-゚]+$")) {
    console.log("全角文字です")
}else {
    console.log("全角文字じゃないです")
}

絵文字や特殊記号なども全角文字として判定されます
厳密な判定が必要な場合はUnicodeでの判定を検討してください

終わりに

文字列のサイズとバイト数の違いから判定する方法も考えましたが、全角文字が全て同じByte数ではないため断念しました。
正規表現は一見難しそうと思いつつ、一つずつ紐解いていくと意味を理解することができました。

参考

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?