简体   繁体   English

如何检查字符串是否仅包含拉丁字符?

[英]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? 我该如何在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. 谢谢。

Similarly as in How can I check if a string contains Chinese in Swift? 如何检查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. \\P{Latin} (大写\\P{Latin} “ P”)是匹配任何具有“ Latin” Unicode字符属性的字符的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM