tags:

views:

70

answers:

2

I have the following code:

            string filterTerm = txtDocFilterTerm.Text.ToLower();
            var regEx = new Regex(filterTerm);

            //griQualifiedDocs is a grid
            //storage.QualifiedDocs is the master/original collection

            griQualifiedDocs.ItemsSource = storage.QualifiedDocs
                .Where(item => regEx.IsMatch(item.DocName.ToLower()))
                .ToList();

This query will return all of the strings that match the filterterm, regardless of it's place in the string. How can I restrict it so the regex is only run against the start of the string?

For example, the current code will return "Joe Jones" and "Jonesy Smith" if the filter is "Jones"; I only want to return "Jonesy Smith"

TIA.

+6  A: 

Use "^" to anchor to the start of a string.

var regEx = new Regex("^" + filterTerm);
Sam
+3  A: 

Why not use this (assuming of course you're not passing in regex expressions):

 griQualifiedDocs.ItemsSource = storage.QualifiedDocs
                .Where(item =>item.DocName.ToLower().StartsWith(filterTerm))
                .ToList();
Agent_9191