5
2

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.

ruby nkf メモ

Last updated at Posted at 2019-09-29

Rubyのnkf のオプションを理解するためのメモ

require 'nkf'
str = "あアぁアヴバパヴ0101abABabAB"

# -w はUTF-8(BOMなし)で出力するオプション nkfはデフォルトで半角カナを全角カナ変換する
NKF.nkf("-w", str)
=> "あアぁアヴバパヴ0101abABabAB"

# -x をつけると半角カナはそのまま出力される
NKF.nkf("-xw", str)
# => "あアぁアヴバパヴ0101abABabAB"

# ひらがなをカタカナに変換
NKF.nkf("-h1 -w", str)
# => "ああぁあゔばぱゔ0101abABabAB"

# カタカナをひらがなに
NKF.nkf("-h2 -w", str)
# => "アアァアヴバパヴ0101abABabAB"

# 全角空白を半角空白に変換
str1 = "育ち盛り 弁当"
NKF.nkf("-Z1 -w", str1)
# => "育ち盛り 弁当"

# 変換元の文字コードをsjisへ変換
NKF.nkf('-s', str)
# => "\x{82A0}\x{8341}\x{829F}\x{8341}\x{8394}\x{836F}\x{8370}\x{8394}01\x{824F}\x{8250}abAB\x{8281}\x{8282}\x{8260}\x{8261}"

# icが入力の文字コード、ocが出力の文字コード、変換できなければ下駄線に置き換える
kbf = "〜鎌倉幕府〜"
sub = NKF.nkf("--ic=UTF-8 --oc=CP932 --fb-subchar=0x3013", kbf)
# => "\x{81AC}\x{8A99}\x{9171}\x{968B}\x{957B}\x{81AC}"

# sjisからUTF8に変換
sub.encode("UTF-8", "Shift_JIS")
# => "〓鎌倉幕府〓"

# UTF8からsjisへ変換
str.encode("Shift_JIS", "UTF-8")
# => "\x{8160}\x{8A99}\x{9171}\x{968B}\x{957B}\x{8160}"
str2 = "てすと😓"

sub2 = NKF.nkf("--ic=UTF-8 --oc=CP932 --fb-subchar=0x3013", str2)
sub2.encode("UTF-8", "Shift_JIS")
# => "てすと〓"
5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?