25
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Web上のコンテンツや入力情報などが、英語か日本語か判別したいときのメモ

Posted at

##判別の仕方

rubyでは、正規表現で「ひらがな」「カタカナ」「漢字」をそれぞれ、

  • ひらがな:/\p{Hiragana}/
  • カタカナ:/\p{Katakana}/
  • 漢字:/[一-龠々]/

で表現できるので、とある文字列に日本語が含まれるかどうかの判定は以下で判別できる。

"#{text}" =~ /(?:\p{Hiragana}|\p{Katakana}|[一-龠々])/

##念のためやってみる。

"test text desu" =~ /(?:\p{Hiragana}|\p{Katakana}|[一-龠々])/
=> nil

"test text です" =~ /(?:\p{Hiragana}|\p{Katakana}|[一-龠々])/
=> 10
#最初の日本語のindexを出力します。

"test テキスト desu" =~ /(?:\p{Hiragana}|\p{Katakana}|[一-龠々])/
=> 5

"test 試験 desu" =~ /(?:\p{Hiragana}|\p{Katakana}|[一-龠々])/
=> 5

###はい、できた!

25
22
0

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
25
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?