Search code examples
swiftchinese-locale

How can I check if a string contains Chinese in Swift?


I want to know that how can I check if a string contains Chinese in Swift?

For example, I want to check if there's Chinese inside:

var myString = "Hi! 大家好!It's contains Chinese!"

Thanks!


Solution

  • This answer to How to determine if a character is a Chinese character can also easily be translated from Ruby to Swift (now updated for Swift 3):

    extension String {
        var containsChineseCharacters: Bool {
            return self.range(of: "\\p{Han}", options: .regularExpression) != nil
        }
    }
    
    if myString.containsChineseCharacters {
        print("Contains Chinese")
    }
    

    In a regular expression, "\p{Han}" matches all characters with the "Han" Unicode property, which – as I understand it – are the characters from the CJK languages.