-2

Here is my string string countCommas = 12,34,56

I am looking for REGEX for algorithm below

BOOL isCountExaclty2 = if(number of commas in string == 2){return TRUE;}else return FALSE

I want the right hand expression as one single REGEX expression which returns either TRUE or FALSE but not the count (I know to use Regex.COUNT..but it ends up in 2 statements)

Cœur
  • 37,241
  • 25
  • 195
  • 267
raj'sCubicle
  • 350
  • 2
  • 13

2 Answers2

0

Try this :

string countCommas = "12,34,56"
bool isCountExaclty2 = Regex.Split(countCommas, ",").Length == 2;
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110
  • thanks for your reply..but I am looking for an expression to Match against..using ISMATCH..the reason for that is I am using some other expressions in combination with this expression..to match against – raj'sCubicle Apr 18 '13 at 13:35
0

If you're looking for a pattern that will only match if there's exactly two commas in the string, this should work:

 bool isCountExactly2 = Regex.IsMatch("12,34,56", "^([^,]*,){2}[^,]*$");

But regular expressions really aren't the right tool for this job.

Sven
  • 21,903
  • 4
  • 56
  • 63
  • Thanks,that is what exactly I am looking for.But what is the downside using Regex.I am new to using Regex.Please explain – raj'sCubicle Apr 18 '13 at 13:31
  • Regular expressions are hard to write, and even harder to read, which makes your code hard to maintain. They also aren't necessarily the fastest option, especially for something like this that you can easily code manually. – Sven Apr 18 '13 at 19:10