Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a string contains only latin characters?

I need to set different font to a label based on whether I'm displaying simple English string or characters from other languages that are not based on the latin characterset. So I just want to know whether if the entire string is all latin characters? How can I do that in Swift? I have read this question, but I don't think I can apply that answer because there is no way I can specify all the latin character including the mark and punctuation, one by one, to be excluded in the detection.

Please help. Thanks.

like image 954
Chen Li Yong Avatar asked Dec 24 '22 16:12

Chen Li Yong


1 Answers

Similarly as in How can I check if a string contains Chinese in Swift?, you can use a regular expression to check if there is no character not in the "Latin" character class:

extension String {
    var latinCharactersOnly: Bool {
        return self.range(of: "\\P{Latin}", options: .regularExpression) == nil
    }
}

\P{Latin} (with capital "P") is the pattern matching any character not having the "Latin" Unicode character property.

like image 52
Martin R Avatar answered Apr 01 '23 03:04

Martin R