Fredo
Fredo

Reputation: 173

How to search array using unknown characters - Swift 3 for Mac

I am looking for a way to search an Array of strings (containing filenames with extension) for dots (if the string contains characters-a dot-charaters, print the string definition). To do that I have to use something like wildcards (.).

So I tried this :

let testString = "*.*"
if Array[x].countains(testString)
{
print (Array[x])
} 

or

if Array[x].range(of:testString) != nil
{
print (Array[x])
}

But it does not work. I guess I have to declare it differently but I don't know how and I have not found the right example. Could someone shows some examples? Thank U.

Upvotes: 1

Views: 157

Answers (1)

Paulo Mattos
Paulo Mattos

Reputation: 19339

Using this helper method on String:

extension String {
    func contains(regex: NSRegularExpression) -> Bool {
        let length = self.utf16.count // NSRanges are UTF-16 based!
        let wholeString = NSRange(location: 0, length: length)
        let matchCount = regex.numberOfMatches(in: self, range: wholeString)            
        return matchCount > 0
    }
}

Then try this:

let fileNameWithExtension = try! NSRegularExpression(pattern: "\\w+[.]\\w+")
if Array[x].contains(regex: fileNameWithExtension) {
    print(Array[x])
}

You may need to tweak my pattern above in order to match all cases you have in mind. This NSRegularExpression cheat sheet might help you there ;-)

Upvotes: 1

Related Questions