jackxujh
jackxujh

Reputation: 1023

Determine if a string only contains invisible characters in Swift

I was parsing a messy XML. I found many of the nodes contain invisible characters only, for instance:

I saw some posts and answers about alphabet and numbers, but the XML being parsed in my project includes UTF8 characters. I am not sure how I can list all visible UTF8 characters in the filter.

How can I determine if a string is made up of completely invisible characters like above, so I can filter them out? Thanks!

Upvotes: 2

Views: 733

Answers (2)

rmaddy
rmaddy

Reputation: 318814

Trim the string of whitespaces and newlines and see what's left.

if someString.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
    // someString only contains whitespaces and newlines
}

Upvotes: 0

Charles Srstka
Charles Srstka

Reputation: 17050

Use CharacterSet for that.

let nonWhitespace = CharacterSet.whitespacesAndNewlines.inverted
let containsNonWhitespace = (string.rangeOfCharacter(from: nonWhitespace) != nil)

Upvotes: 2

Related Questions