How to check string with specific format using regex?

97 Views Asked by At

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.

3

There are 3 best solutions below

1
ASh On BEST ANSWER

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$");
1
The fourth bird On

If you want to check a single line without optional leading zeroes, in C# you can use:

\AX[1-9][0-9]?Y[1-9][0-9]?  Z\z

Regex demo

1
jdweng On

The question mark which is optional parameters are giving you issues. Instead of the question mark use {1,2} which is one or two times like code below

          string[] inputs = {"X5Y9  Z","X1Y20  Z","X35Y2  Z","X20Y99  Z","X01Y05  Z",
                  "X2Y09  Z","X77Y08  Z","X05Y9  Z","X01Y29  Z","X123Y456  Z"};
            string pattern = @"^X\d{1,2}Y\d{1,2}\s\sZ";

            foreach(string input in inputs)
            {
                Match match = Regex.Match(input, pattern);
                Console.WriteLine("Input : {0}, Match : {1}", input, match.Success ? "True" : "False");
            }
            Console.ReadLine();