Home
Manage Your Code
Snippet: Combine LINQ Queries with Regular Expressions (C#)
Title: Combine LINQ Queries with Regular Expressions Language: C#
Description: This example shows how to use the Regex class to create a regular expression for more complex matching in text strings. Views: 453
Author: Mark Henderson Date Added: 5/6/2008
Copy Code  
1class QueryWithRegEx
2{
3    public static void Main()
4    {
5        // Modify this path as necessary.

6        string startFolder = @"c:\program files\Microsoft Visual Studio 9.0\";
7
8        // Take a snapshot of the file system.
9        IEnumerable<System.IO.FileInfo> fileList = GetFiles(startFolder);
10
11        // Create the regular expression to find all things "Visual".
12        System.Text.RegularExpressions.Regex searchTerm = 
13            new System.Text.RegularExpressions.Regex(@"Visual (Basic|C#|C\+\+|J#|SourceSafe|Studio)");
14
15        // Search the contents of each .htm file.
16        // Remove the where clause to find even more matches!
17        // This query produces a list of files where a match
18        // was found, and a list of the matches in that file.
19        // Note: Explicit typing of "Match" in select clause.
20        // This is required because MatchCollection is not a 
21        // generic IEnumerable collection.
22        var queryMatchingFiles =
23            from file in fileList
24            where file.Extension == ".htm"
25            let fileText = System.IO.File.ReadAllText(file.FullName)
26            let matches = searchTerm.Matches(fileText)
27            where searchTerm.Matches(fileText).Count > 0
28            select new
29            {
30                name = file.FullName,
31                matches = from System.Text.RegularExpressions.Match match in matches
32                          select match.Value
33            };
34
35        // Execute the query.
36        Console.WriteLine("The term \"{0}\" was found in:", searchTerm.ToString());
37
38
39        foreach (var v in queryMatchingFiles)
40        {
41            // Trim the path a bit, then write 

42            // the file name in which a match was found.

43            string s = v.name.Substring(startFolder.Length - 1);
44            Console.WriteLine(s);
45
46            // For this file, write out all the matching strings

47            foreach (var v2 in v.matches)
48            {
49                Console.WriteLine("  " + v2);
50            }
51        }
52
53        // Keep the console window open in debug mode

54        Console.WriteLine("Press any key to exit");
55        Console.ReadKey();
56    }
57
58    // This method assumes that the application has discovery 

59    // permissions for all folders under the specified path.

60    static IEnumerable<System.IO.FileInfo> GetFiles(string path)
61    {
62        if (!System.IO.Directory.Exists(path))
63            throw new System.IO.DirectoryNotFoundException();
64
65        string[] fileNames = null;
66        List<System.IO.FileInfo> files = new List<System.IO.FileInfo>();
67
68        fileNames = System.IO.Directory.GetFiles(path, "*.*", System.IO.SearchOption.AllDirectories);
69        foreach (string name in fileNames)
70        {
71            files.Add(new System.IO.FileInfo(name));
72        }
73        return files;
74    }
75}
76
Notes
http://msdn.microsoft.com/en-us/library/bb882639.aspx