File name globbing in Swift

I want to check if a given string matches a file pattern. Does Swift have builtin support for filename globbing? Or is there any 3rd party packages for this?

Answered by DTS Engineer in 780486022

I use fnmatch for this. It’s a C API but quite nice to call from Swift:

let txtMatches = fnmatch("*.txt", "hello.txt", 0) == 0
let jpgMatches = fnmatch("*.txt", "hello.jpg", 0) == 0
print(txtMatches, jpgMatches)
// prints: true false

See the fnmatch man page for more details.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

I believe you're looking for RegEx: https://developer.apple.com/documentation/swift/regex

Accepted Answer

I use fnmatch for this. It’s a C API but quite nice to call from Swift:

let txtMatches = fnmatch("*.txt", "hello.txt", 0) == 0
let jpgMatches = fnmatch("*.txt", "hello.jpg", 0) == 0
print(txtMatches, jpgMatches)
// prints: true false

See the fnmatch man page for more details.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

File name globbing in Swift
 
 
Q