After a long break, Eric is back, and continue his awesome RegEx 101 exercise series, in this exercise, the question Eric asks is:
Bytes -------------------------------------------------------------------------------------------------
Given a string like:
#4 6 #7 #45 #43 #65 56 2 #4345 #23
Count how many numbers there are in this string
Bytes --------------------------------------------------------------------------------------------------
I have three simple solutions to this problem.
Solution #1: RegEx = new RegEx (@ "\ D +", regexoptions. ignorecase );
String inputstring = @ "#4 6 #7 #45 #43 #65 56 2 #4345 #23 ";
Int32 COUNT = 0;
RegEx. Replace (inputstring, delegate (match)
{
Count ++;
Return string. empty;
});
Console. writeline (count );
Solution #2: RegEx = new RegEx (@ "\ D +", regexoptions. ignorecase );
String inputstring = @ "#4 6 #7 #45 #43 #65 56 2 #4345 #23 ";
Matchcollection matches = RegEx. Matches (inputstring );
Console. writeline (matches. Count );
Solution #3: RegEx = new RegEx (@ "[# \ s] +", regexoptions. ignorecase );
String inputstring = @ "#4 6 #7 #45 #43 #65 56 2 #4345 #23 ";
String [] values = RegEx. Split (inputstring );
Console. writeline (values. Length-1 );
Side note: For all of you who are interested in regluar expressions, and want to be more proficient at it, I encourage you to actively participant ipate in Eric Gunnerson's RegEx exercises, at the end of day, you will find that you benefit a lot in that process.