After reading documentations, examples, and playing with the code myself, I can finally understand how to achieve what was so easy to do in PERL using the class hierarchy of ASP.NET.
This post is intended for people who know what are regular expressions, and want to understand how to implement them in C#.
This is what I needed to do:
I had a string consisting of some prefix, underscore and then a number: {prefix}
I wanted to get the number from that string.
The PERL way would be something like
my ($num) = $my_string =~ /_([0-9]+)$/
That's it... so simple.
Now this is how I did it in C#:
Match match = Regex.Match(my_string, @"_(?<num>[0-9]+)$");
int num = Int32.Parse(match.Groups["num"].ToString());
I used named grouping - I called the group I was looking for by a name, "num".
First I tried it without naming - omitting the ?
It is quite confusing (and not really documented, at least where I was looking) so it seems clearer to me to remain with the named groups.
No comments:
Post a Comment