开发者

How to specify to Regex (in a LINQ Query) to only compare the start of a string?

开发者 https://www.devze.com 2022-12-14 19:14 出处:网络
I have the following code: string filterTerm = txtDocFilterTerm.Text.ToLower(); var regEx = new Regex(filterTerm);

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 "J开发者_运维百科onesy Smith" if the filter is "Jones"; I only want to return "Jonesy Smith"

TIA.


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

var regEx = new Regex("^" + filterTerm);


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消