1

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.

2
  • 3
    Are you sure those are null terminators? It seems like the backslash character, followed by x followed by 2 zeros. Commented Jul 24, 2018 at 0:38
  • You are right. These are not null terminators. Not sure why i am getting that string for the external source. Guess i'd have to figure that out Commented Jul 24, 2018 at 3:05

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.