Search code examples
c#regexstringvalidationformat-string

How to check string with specific format using regex?


I have a specific format string and the result looks like that

X5Y9  Z : true
X1Y20  Z : true
X35Y2  Z : true
X20Y99  Z : true

X01Y05  Z : false
X2Y09  Z : false
X77Y08  Z : false
X05Y9  Z : false
X01Y29  Z : false
X123Y456  Z : false

I try to use "Regex" to check whether a specific string is a correct format or not. Note that, the cases that start with 0 will be excluded, and it only has a value from 1-99, like this

XxxYyy Z

xx only accepts values from 1-99
yy only accepts values from 1-99

The behind code look that

if (Regex.IsMatch(str, @"^X([0]?[1-9]{1,2})Y([0]?[1-9]{1,2})  Z$"))
    flag = true;
else
    flag = false;

But it does not seem to work, So, I don't know if have any mistake for this regex. Anything to find, please share it with us. Thank you all.


Solution

  • using [0]? means that single 0 symbol is allowed in that postion, which contradicts the rule

    flag = Regex.IsMatch(str, @"^X([1-9]\d?)Y([1-9]\d?)  Z$");