惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Cloudflare Blog
有赞技术团队
有赞技术团队
H
Help Net Security
V
Visual Studio Blog
F
Fortinet All Blogs
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 司徒正美
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
腾讯CDC
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Stack Overflow Blog
Stack Overflow Blog
I
InfoQ
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
L
LangChain Blog
N
Netflix TechBlog - Medium
罗磊的独立博客
The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
Hugging Face - Blog
Hugging Face - Blog
A
About on SuperTechFans
aimingoo的专栏
aimingoo的专栏
Recent Announcements
Recent Announcements

博客园 - Sheva

Two Xaml Tricks - Sheva I See Cool Stuff Today DataTemplate Is A Bit Naughtier To Play With XmlnsDefinitionAttribute Is Pretty Nifty Application.DoEvents In WPF 征召译者 C# Trivia Test CreateParams Is Pretty Cool! In-Place Editing In WPF SingleLinkedList Implementation Data Binding In WPF C# Application Markup Language Regex 101 Exercise I10 - Extract repeating hex blocks from a string AvalonPaint: Features Added Crossbow: Hosting WPF Controls In Winforms Application Crossbow? WTF? The Architecture Of Avalon Drop Shadow Effect In WPF XamlReader.Load(): Build Up Your Own XamlPad
Regex 101 Exercise I9 - Count the number of matches
Sheva · 2006-03-01 · via 博客园 - Sheva

    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.