c# - Error when counting a specific word in a string with Regex.Matches -
i tried find method count specific word in string, , found this.
using system.text.regularexpressions; matchcollection matches = regex.matches("hi, hi, everybody.", ","); int cnt = matches.count; console.writeline(cnt);
it worked fine, , result shows 2. when change "," ".", shows 18, not expected 1. why?
matchcollection matches = regex.matches("hi, hi, everybody.", ".");
and when change "," "(", shows me error! error reads:
system.argumentexception - there many (...
i don't understand why happening
matchcollection matches = regex.matches("hi( hi( everybody.", "(");
other cases seem work fine need count "(".
the first instance, .
, using special character has different meaning in regular expressions. matching of characters have; hence getting result of 18.
http://www.regular-expressions.info/dot.html
to match actual "." character, you'll need "escape" read full-stop , not special character.
matchcollection matches = regex.matches("hi, hi, everybody.", "\.");
the same exists (
character. it's special character has different meaning in terms of regular expressions , need escape it.
matchcollection matches = regex.matches("hi( hi( everybody.", "\(");
looks you're new regular expressions i'd suggest reading, link posted above start.
however!
if looking count ocurences in string, don't need regex.
how count occurrences of string within string?
if you're using .net 3.5 can in one-liner linq:
int cnt = source.count(f => f == '(');
if don't want use linq can with:
int cnt = source.split('(').length - 1;
Comments
Post a Comment