Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a regular expression on a String using Linq

I have a String, I wish to use Linq to run a regular expression to cut down my string to a smaller sub-string which matches my reg ex.

My code at the moment gives the error

'char' does not contain a definition for 'Name' and no extension method 'Name' accepting a first argument of type 'char' could be found

My code :

string variable = result.Name.Select(r => regEx.Match(r.Name).Groups[2].ToString());

Result.Name is a string contained in a custom class.

What have I done incorrectly? What is wrong with my syntax/understanding ?

like image 563
Simon Kiely Avatar asked May 17 '12 14:05

Simon Kiely


2 Answers

Are you looking for something like this?

string[] result = Regex.Matches(input, pattern)
                       .Cast<Match>()
                       .Select(match => match.Groups[2].Value)
                       .ToArray();
like image 198
dtb Avatar answered Sep 24 '22 23:09

dtb


You're calling Select on a single string. Select is treating your string as a series of characters, and so the r in your lambda expression is a char.

If you only have a single string you want to pass into your regular expression, and you only want a single match out, then you don't need LINQ at all. Just call

string variable = regEx.Match(result.Name).Groups[2].ToString();

(I'm assuming result.Name is your single string, based on your example code.)

like image 28
Rawling Avatar answered Sep 26 '22 23:09

Rawling