David Soler David Soler - 11 days ago 6
C# Question

Regex n 0 and then a 1

I am looking for a regex to match n zeros and then a 1.
E.g:

0000100 -> matches
00200 -> does not math


I thought it was something like that:

var regex = new Regex(@"[0]*[2-9]+");

Answer

Linq solution (and no regular expression):

string source = "0001";

bool isValid = source
  .SkipWhile(c => c == '0')
  .FirstOrDefault() == '1';

If you insist on regular expression:

bool isValid = Regex.IsMatch(source, "^0*1");

In both cases zero or more 0 followed by 1