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?

More than 3 years have passed since last update.

DataWeaveで全角カナを半角に変換

Posted at

DataWeaveで全角カナ文字列を、半角カナに変換する

提案なのか、お客様プロジェクト向けなのか分かりませんが、同僚が全角から半角への変換について社内で質問してましたので、DataWeaveの勉強がてら考えてみました。
私が確認できた方法は2つ。

方法1: Javaのクラスを利用する

Anypoint Studioでは、Javaのクラスを作成し、DataWeaveからそのクラスのStaticメソッドを呼び出すことが可能となっており、その仕組みを利用した方法です。

まず、下記のようなクラスを、src/main/javaに作成します。

import com.ibm.icu.text.Transliterator;
public class hankaku {
	public static String ztoh(String str) {
		Transliterator transliterator = Transliterator.getInstance("Fullwidth-Halfwidth");
		String result = transliterator.transliterate(str);
		return result;
	}
}

そして、DataWeaveからはこのようにimport java!クラスで呼び出します。

%dw 2.0
import java!hankaku
output applidation/dw
---
hankaku::ztoh("アイウエオ")

実行結果はこんな感じ。(Anypoint StudioのTransform Message)
image.png

方法2: 文字コードで変換する

もう一つは、全角ア~ンから、半角ア~ンへの変更とはなりますが、文字コードを利用する方法を試してみました。
全角ア~ンは、Unicodeで12450から12531で、一つ飛ばし。
半角ア~ンは、65393から65437となります。
下記のコードでは、対象の文字列の長さ分の配列を作り、全角カナの範囲であれば半角カナの文字コードを計算して文字を当てはめてます。
最後に、JoinByでくっつけて完成。
これであれば、DataWeaveのみの実装になっています。

%dw 2.0
import dw:core:Strings
output application/dw
var str = "アイウエオあいうえお"
var arr = 0 to sizeOf(str) -1
var dat = do {
  arr map (item,index) -> {
    char:  if(12450 <= Strings::charCodeAt(str, item) and Strings::charCodeAt(str, item) < 12531) Strings::fromCharCode((Strings::charCodeAt(str, item) - 12450)/2+65393)
    else Strings::fromCharCode(Strings::charCodeAt(str, item))
  }
}
---
 dat.char joinBy ""

下記は、DataWeave Playgroundで試した結果です。

image.png

1
0
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
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?