-------------------------------------------------------------------------------------------------
Given a string like:
# # 4 6 # # 7 # 45 # 43 # 65 56 2 # 4345 # # 23
Count how many numbers there are in this string
--------------------------------------------------------------------------------------------------I have three simple solutions to this problem.
Solution #1:
Regex 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 match)
{
count++;
return String.Empty;
});
Console.WriteLine(count);
String inputString = @"# # 4 6 # # 7 # 45 # 43 # 65 56 2 # 4345 # # 23";
Int32 count = 0;
regex.Replace(inputString, delegate(Match match)
{
count++;
return String.Empty;
});
Console.WriteLine(count);
Solution #2:
Regex 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);
String inputString = @"# # 4 6 # # 7 # 45 # 43 # 65 56 2 # 4345 # # 23";
MatchCollection matches = regex.Matches(inputString);
Console.WriteLine(matches.Count);
Solution #3:
Regex 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);
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 participate in Eric Gunnerson's regex exercises, at the end of day, you will find that you benefit a lot in that process.