0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Swift】文字列が英語かそうじゃないかを判定する

Posted at

実現したいこと

  • 文字列Textが英語か英語以外かを判定する

取り組んだこと

  • 正規表現を用いれば実現可能だと思った。
struct CustomText: ViewModifier {
    let contentText: String
    let regex = "^[A-Za-z]+$"
 
    func body(content: Content) -> some View {
        var array_text = Array(contentText).map{String($0)}
        HStack {
            ForEach(array_text, id: \.self) { item in
                if item.wholeMatch(of: regex) {
                    Text(item)
                        .font(.custom("Futura", size: 20))
                } else {
                    Text(item)
                        .font(.custom("HiraginoSans-W6", size: 20))
                }
            }
        }
    }
}

  • ここまで書いて、Regexの型の扱いがやや面倒だったことと、コードが冗長な気がしたのでもっと短くできると思った。

解決策

  • Stringを拡張して文字列の言語を判定するロジックを利用する。
extension String {
    // ひらがなかどうか
    var isHiragana: Bool {
        let range = "^[ぁ-ゞ  ]+$"
        return NSPredicate(format: "SELF MATCHES %@", range).evaluate(with: self)
    }
    // カタカナかどうか
    var isKatakana: Bool {
        let range = "^[ァ-ヾ]+$"
        return NSPredicate(format: "SELF MATCHES %@", range).evaluate(with: self)
    }
    // 英数字かどうか
    var isAlphanumeric:Bool {
        let range = "[a-zA-Z0-9]+"
        return NSPredicate(format: "SELF MATCHES %@", range).evaluate(with: self)
    }
}
  • すると、かなりスッキリと判定をすることができる。
{StringName}.isAlphanumeric == true 

謝辞

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?