Volunteer .NET Evangelist

A well oiled machine can’t run efficiently, if you grease it with water.
  首页  :: 联系 :: 订阅 订阅  :: 管理

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:
-------------------------------------------------------------------------------------------------

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);

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);

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);

    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.