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

javaでマスク処理(置き換え)

Last updated at Posted at 2024-10-22

住所マスク

public class AddressMasker {
    public String maskAddress(String address) {
        // 正規表現パターンの定義(全角数字 + ('ー' + 全角数字)の繰り返し)
        String pattern = "[0-9]+(?:ー[0-9]+)+";
        
        if (address.matches(".*" + pattern + ".*")) {
            // マッチする場合、置換を用いてマスキング
            // 全角スペースと全角数字、'ー'以外を'*'に置換
            String maskedAddress = address.replaceAll("[^ 0-9ー]", "*");
            return maskedAddress;
        } else {
            // マッチしない場合、住所の下5文字以外をマスク
            int unmaskLength = 5;
            if (address.length() <= unmaskLength) {
                return address; // 住所が短い場合はそのまま返す
            } else {
                String maskedPart = address.substring(0, address.length() - unmaskLength).replaceAll(".", "*");
                String unmaskedPart = address.substring(address.length() - unmaskLength);
                return maskedPart + unmaskedPart;
            }
        }
    }

    // テスト用メインメソッド
    public static void main(String[] args) {
        AddressMasker masker = new AddressMasker();
        String address1 = "東京都新宿区 1ー2ー3";
        String address2 = "大阪府大阪市1丁目2番3号";
        System.out.println("マスク結果1:" + masker.maskAddress(address1));
        System.out.println("マスク結果2:" + masker.maskAddress(address2));
    }
}

郵便番号マスク

public class ZipCodeMasker {
    public static void main(String[] args) {
        String zipCode = "123ー456";
        String maskedZipCode = maskZipCode(zipCode);
        System.out.println(maskedZipCode); // 期待値:***ー***
    }

    public static String maskZipCode(String zipCode) {
        if (zipCode == null || zipCode.isEmpty()) {
            return zipCode;
        }

        return zipCode.replaceAll("[^ー]", "*");
    }
}
0
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
0
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?