-3

I'm trying to count how many * symbols i have in my string. however im getting an error.

An unhandled exception of type 'System.ArgumentException' occurred in System.dll

I'm simply using a regex match to check it. When i tested with any other string it worked perfectly, but when i search for " * " it get's an exception.

Here's the code that gives expresion

string abc = "i am just trying *** for a sample code";
var count = Regex.Matches(abc, "*").Count;
Console.Out.WriteLine(count);

This one works perfectly

string abc = "i am just trying  for a sample code";
var count = Regex.Matches(abc, "a").Count;
Console.Out.WriteLine(count);

Any Idea why ?

DhavalR
  • 1,409
  • 3
  • 29
  • 57
Nanopl
  • 77
  • 1
  • 13
  • The error message would be helpful. – rory.ap May 07 '18 at 11:29
  • *"any idea why"* - yes, the `*` character is a so-called [quantifier](https://www.regular-expressions.info/repeat.html) and it therefore must be escaped. – Thomas Flinkow May 07 '18 at 11:29
  • 1
    You should really quote the full details of the exception in your question. In this case I assume the exception message says something like: `parsing "*" - Quantifier {x,y} following nothing.` – Chris May 07 '18 at 11:30
  • This is such a duplicate question, but has answers anyway. – SᴇM May 07 '18 at 11:39

3 Answers3

11

You could use LINQ Count instead:

string abc = "i am just trying *** for a sample code";
var result = abc.Count(c=>c=='*');
Slaven Tojić
  • 2,945
  • 2
  • 14
  • 33
  • In theory this can be improved in some cases (particularly if the string is long and the target characters are near the start) by avoiding counting every single occurrence, and stopping as soon as a duplicate is found: `bool dups = s.SkipWhile(c => c != '*').Skip(1).Any(c => c == '*');` – Matthew Watson May 07 '18 at 12:14
6

* is a metacharacter and needs to be escaped

var count = Regex.Matches(abc, @"\*").Count;
fubo
  • 44,811
  • 17
  • 103
  • 137
2

* has special meaning on a regex, you should escape it with \. Try:

var count = Regex.Matches(abc, @"\*").Count;
apomene
  • 14,282
  • 9
  • 46
  • 72