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

时间:2017-07-12 08:16:58

标签: swift string unicode

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.

1 个答案:

答案 0 :(得分:6)

How can I check if a string contains Chinese in Swift?类似, 您可以使用正则表达式来检查是否没有字符 “拉丁”字符类中

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

\P{Latin}(大写字母“P”)是匹配任何字符而不是具有“拉丁”Unicode字符属性的模式。