Determine if a string only contains invisible characters in Swift

Viewed 463

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

  • "\n "
  • " "
  • "\t "
  • "\n "
  • "\n\n"

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!

2 Answers

Use CharacterSet for that.

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

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

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