user3196085
user3196085

Reputation:

How to get an only element from the MatchCollection

I know that there is always only one element in MatchCollection:

Regex reg = new Regex("1234");
MatchCollection matches = reg.Matches("fjasij 1234 gdsgds");
Console.WriteLine(matches.Count);
string s = ?;

How to assign this one element to the variable string s without foreach loop?

Upvotes: 6

Views: 4177

Answers (2)

Simon Whitehead
Simon Whitehead

Reputation: 65077

Why use a MatchCollection then? Just get a single Match:

var match = reg.Match("fjasij 1234 gdsgds");

Upvotes: 13

System Down
System Down

Reputation: 6270

string s = matches[0];

Note that this will fail if you have zero matches.

Upvotes: 6

Related Questions