Take the 2-minute tour ×

I am new to regular expressions. Recently I was presented with a task to convert a wildcard pattern to regular expression. This will be used to check if a file path matches the regex.

For example if my pattern is *.jpg;*.png;*.bmp

I was able to generate the regex by spliting on semicolons, escaping the string and replaceing the escaped * with .*

String regex = "((?i)" + Regex.Escape(extension).Replace("\\*", ".*") + "$)";

So my resulting regex will be for jpg ((?i).*\.jpg)$) Thien I combine all my extensions using the OR operator.

Thus my final expression for this example will be:


I have tested it and it worked yet I am not sure if I should add or remove any expression to cover other cases or is there a better format the whole thing

Also bear in mind that I can encounter a wildcard like *myfile.jpg where it should match all files whose names end with myfile.jpg

I can encounter patterns like *myfile.jpg;*.png;*.bmp

share|improve this question
you might also try codereview.se –  Dan-o Oct 2 '12 at 19:12
I find using refiddle.com to be very useful for testing out regular expressions. –  jussinen Oct 2 '12 at 19:24
Well i have been testing my expressions yet testing could be a problem if you have a hunch that you are missing something or overthinking the issue –  Red Serpent Oct 2 '12 at 19:33

1 Answer 1

up vote 8 down vote accepted

There's a lot of grouping going on there which isn't really needed... well unless there's something you haven't mentioned this regex would do the same for less:


That's in regex notation, in C# that would be:

String regex=new RegEx(@".*\.(jpg|png|bmp)$",RegexOptions.IgnoreCase);

If you have to programatically translate between the two, you've started on the right track - split by semicolon, group your extensions into the set (without the preceding dot). If your wildcard patterns can be more complicated (extensions with wildcards, multi-wildcard starting matches) it might need a bit more work ;)

Edit: (For your update)

If the wild cards can be more complicated, then you're almost there. There's an optimization in my above code that pulls the dot out (for extension) which has to be put back in so you'd end up with:


Basically '*' -> '.*', '.' -> '\.'(gets escaped), rest goes into the set. Basically it says match anything ending (the dollar sign anchors to the end) in myfile.jpg, .png or .bmp.

share|improve this answer
What about filenames, for wildcards like myfile.jpg for example. Assume such pattern *myfile.jpg;.png –  Red Serpent Oct 2 '12 at 19:18
I edited the question, sorry I did not mention the last issue first hand. So can your expression be modified to include such a case? –  Red Serpent Oct 2 '12 at 19:34

Your Answer


