DOS-like Wildcard for Filtering List of Files [duplicate]

This question already has an answer here:

How do I perform string matching and replacements?

2 answers

I have a list of file names that I would wild like to filter based on a DOS like wildcard specification similar to what can be used as the first argument,”forms”, of FileNames[]. I don’t need full compatibility, but something so that “*.txt” returns a list of the text files and “*2015*.log” returns stuff like “c:\logfiles\2015\Dec\logfile.log” out of my list. Apologies if this is a repeat but I couldn’t find any similar questions.



1 Answer


You can use StringMatchQ to test for matches.

Select[{“foo”, “bar”, “baz”}, StringMatchQ[“ba*”]]
(* {“bar”, “baz”} *)

There are three ways to specify a string pattern in StringMatchQ.

The most basic one uses wildcards like the ones you describe. * stands for zero or more characters. @ stands for one more more character except uppercase letters. They can be escaped inside of a string as “\\*” to match a literal *.

These wildcards are used in many other Mathematica functions such as Information, Names, Clear, etc. As far as I know this syntax is old, available since the earliest versions of Mathematica. If you think about how these wildcards are used to match symbol names, the usefulness (and special properties) of @ becomes clear in light of Mathematica’s CamelCase convention.

The second way is to use string patterns. These are made to look like expression patterns but work with strings. If you already know how to use expression patterns, you’ll pick up string patterns in a minute: all you need to learn is that ~~ is used to connect pieces of the pattern. They were introduced in version 5.1. Here’s the detailed tutorial.

Select[{“foo”, “bar”, “baz”}, StringMatchQ[“ba” ~~ ___]]

Internally string patterns are converted to regular expressions and processed using PCRE.

You can write regular expressions directly as well: look up RegularExpression.

Select[{“foo”, “bar”, “baz”}, StringMatchQ@RegularExpression[“ba.*”]]