









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);
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);
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);
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。