Reputation: 1056
I receive a json array of strings from an external source and some of my string look like
"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00"
I would like to filter out all strings that only contain these null values. I've tried this
arr = arr.filter { (str: String) -> Bool in
let invalid = String(data: Data.init(count: str.count), encoding: String.Encoding.utf8)
print(str)
return str == invalid
}
Since these are all null terminators, i decided to create a null string of the same length as str
but only containing null terminators and compare them.
But this doesn't work. Any help will be appreciated.
Upvotes: 1
Views: 342
Reputation: 273115
I don't think those are null terminators because the backslashes are escaped. Those are just the four character sequence \x00
repeated multiple times.
To match such a pattern, you can use regular expressions:
let regex = try! NSRegularExpression(pattern: "^(?:\\\\x00)+$", options: [])
let string = "\\x00\\x00\\x00\\x00\\x00"
// the below will evaluate to true if the string is full of \x00
regex.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.count)) != nil
Upvotes: 2