您的位置:首页 > 其它

Regex 101 Exercise I9 - Count the number of matches

2006-03-01 21:22 423 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: