Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to find the number of periods(.) in a string

I am getting 140 when I should when I should only get 2.
I do not understand the reason why.
I guessing it don't work with special characters but work with letters.

What I have tried:

string period = ".";
               Regex searchFor = new Regex(period);
               int numOfPeriod = searchFor.Matches(SBDuties).Count;
               Response.Write(period +"<br/>");

               Response.Write("Number of full stops " + numOfPeriod +"<br/>");
               Response.Write(SBDuties);
Posted
Updated 14-Jun-17 8:17am

Quote:
I am trying to find the number of periods(.) in a string

You are using RegEx, it happen that some chars have a special meaning in RegEx, and you are lucky because '.' is a special char that match any char.

Regex is a powerful tool, but like with any tool, you need to learn how to use it.

Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
 
Share this answer
 
There are other options besides RegEx that perform very well. See c# - How would you count occurrences of a string within a string? - Stack Overflow[^] for several good alternatives.
 
Share this answer
 
Comments
[no name] 14-Jun-17 14:40pm    
a 5 for the alternatives
ZurdoDev 14-Jun-17 14:44pm    
Thanks.
string period = "[.]";
 
Share this answer
 
Comments
ZurdoDev 14-Jun-17 14:44pm    
A little explanation?
Matt T Heffron 14-Jun-17 18:58pm    
Wouldn't
  string period = @"\.";
work even more simply?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900