Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find files according RegEx in C#

I need to get list of files on some drive with paths that matches specific pattern, for example FA\d\d\d\d.xml where \d is digit (0,1,2..9). So files can have names like FA5423.xml.

What is the most efficient name to do this?

like image 607
bao Avatar asked May 11 '10 09:05

bao


People also ask

How do I find a file in regex?

In order to search files using a regular expression, select the 'File Name' file matching rule, select the 'RegEx' pattern matching operator and enter a regular expression that should be matched. For example, the '\. (JPG|BMP|PNG)$' regular expression will match all JPG, BMP and PNG image files.

How do I match a pattern in regex?

2.1 Matching a Single Character The fundamental building blocks of a regex are patterns that match a single character. Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" .

How do I find a character in regex?

Match any specific character in a setUse square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.

What does (? I do in regex?

All modes after the minus sign will be turned off. E.g. (? i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode. Not all regex flavors support this.


2 Answers

Are you using C# 3?

Regex reg = new Regex(@"^FA[0-9]{4}\.xml$");
var files = Directory.GetFiles(yourPath, "*.xml").Where(path => reg.IsMatch(path));
like image 90
Phil Gan Avatar answered Sep 16 '22 14:09

Phil Gan


You could do something like:

System.IO.Directory.GetFiles(@"C:\", "FA????.xml", SearchOption.AllDirectories);

Then from your results just iterate over them and verify them against your regex i.e. that the ? characters in the name are all numbers

like image 34
James Avatar answered Sep 18 '22 14:09

James