Regex 101 Exercise I9 - Count the number of matches
Posted on 2006-03-01 21:22 Sheva 阅读(1317) 评论(0) 编辑 收藏 举报
After a long break, Eric is back, and continue his awesome Regex 101 Exercise series, in this exercise, the question Eric asks is:
-------------------------------------------------------------------------------------------------
I have three simple solutions to this problem.
Solution #1:
Solution #2:
Solution #3:
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.
-------------------------------------------------------------------------------------------------
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.