Click here to Skip to main content
15,905,071 members
Please Sign up or sign in to vote.
4.60/5 (2 votes)
See more:
I used the following code to find the matches string within a string.

C#
int x = Regex.Matches("I am good bad good bad bad boy", "bad").Count;

Here output x=3.

Now follow my problem.
C#
int x = Regex.Matches("I have a Voucher in AllVoucher", "Voucher").Count;

Here output x=2!

This program also count Voucher from AllVoucher. But I want to count Voucher where Voucher can start with anything(like -Voucher, .Vouchar) except letter. Like

C#
int x = Regex.Matches("I have a -Voucher in /Voucher", "Voucher").Count;

here expected output x=2;

But for the following line expected out is x=1;

C#
int x = Regex.Matches("I have a Voucher in AllVoucher", "Voucher").Count;

Here output x=2!



Please give me a solution using C#.NET. How can I count matches string where matches string can start with anything except letter.
Posted

C#
int CountWords(string input, string wordToFind)
{
    string pattern = string.Format(@"\b{0}\b", wordToFind);

    return Regex.Matches(input, pattern).Count;
}


You can call this method like this:

e.g.
C#
int count = CountWords("I have a -Voucher in /Voucher", "Voucher")
 
Share this answer
 
Comments
sachi Dash 19-Feb-15 4:11am    
Many Many Thanks !
TheRealSteveJudge 19-Feb-15 4:26am    
You're welcome!
sachi Dash 10-Mar-15 9:23am    
hello how are you? For the following
input:select rp_site.[user] as '[siteq1].[user_ip]'
wordToFind: rp_site.
here I get count=0; why ? please give me a solution. but rp_site. is here in input string. then why count get 0 instead of 1 ? please help me.
TheRealSteveJudge 10-Mar-15 10:24am    
Thank you, I'm fine and you?
I just tried
MessageBox.Show(CountWords("input:select rp_site.[user] as '[siteq1].[user_ip]'", "rp_site").ToString());
It shows "1"
string source = "I am good bad good bad bad boy";
int count = source.Count(f => f == 'bad');
 
Share this answer
 
v2
Comments
CHill60 19-Feb-15 18:02pm    
No. Produces compile error "Too many characters in character literal" and the intent does not address the problem given in the question with "I have a -Voucher in /Voucher" should return 2 but "I have a Voucher in AllVoucher" should return 1
manak chand 20-Feb-15 1:55am    
Use double quote near bad...

string source = "I am good bad good bad bad boy";
int count = source.Count(f => f == "bad");

CHill60 20-Feb-15 4:29am    
And that will produce the compile error "Operator '==' cannot be applied to operands of type 'char' and 'string'" and still does not address the problem as stated

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