LoginSignup
14
12

More than 5 years have passed since last update.

Goで全角英数字を半角にする

Posted at

方法1: unicode.SpecialCase を定義して strings.ToLowerSpecial で半角にする

package main

import (
    "fmt"
    "strings"
    "unicode"
)

var alphanumConv = unicode.SpecialCase{
    // numbers
    unicode.CaseRange{
        Lo: 0xff10, // '0'
        Hi: 0xff19, // '9'
        Delta: [unicode.MaxCase]rune{
            0,
            0x0030 - 0xff10, // '0' - '0'
            0,
        },
    },
    // uppercase letters
    unicode.CaseRange{
        Lo: 0xff21, // 'A'
        Hi: 0xff3a, // 'Z'
        Delta: [unicode.MaxCase]rune{
            0,
            0x0041 - 0xff21, // 'A' - 'A'
            0,
        },
    },
    // lowercase letters
    unicode.CaseRange{
        Lo: 0xff41, // 'a'
        Hi: 0xff5a, // 'z'
        Delta: [unicode.MaxCase]rune{
            0,
            0x0061 - 0xff41, // 'a' - 'a'
            0,
        },
    },
}

func main() {
    strs := []string{
        "0123456789",
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
        "abcdefghijklmnopqrstuvwxyz",
    }
    for _, s := range strs {
        s = strings.ToLowerSpecial(alphanumConv, s)
        fmt.Println(s)
    }
}
出力
0123456789
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz

方法2: normパッケージで正規化

package main

import (
    "fmt"
    "golang.org/x/text/unicode/norm"
)

func main() {
    strs := []string{
        "0123456789",
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
        "abcdefghijklmnopqrstuvwxyz",
    }
    for _, s := range strs {
        s = string(norm.NFKC.Bytes([]byte(s)))
        fmt.Println(s)
    }
}
出力
0123456789
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz

normパッケージでの正規化では目的の全角英数字の半角への変換だけでなく、半角カナを全角にする(「ペンギン」->「ペンギン」)などの変換も行われるので用途に応じて方法を選択する

参考

14
12
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
14
12