SHRI
SHRI

Reputation: 2466

Regular expression class in C#

I have this regular expression below

^(((\s*0[xX]([0-9a-fA-F]{2}))\s*)*)

which will accept only

0x12 0x34 0xA2

It should reject

0x12, 0x34

I am using like this,

if(true != Regex.IsMatch(inputData, @"^(((\s*0[xX]([0-9a-fA-F]{2}))\s*)*)"))
{
Console.WriteLine("error");
}

But even if I give 0x12, 0x34 or any string, it is always giving true. Can somebody solve this please? Thanks

Upvotes: 1

Views: 218

Answers (2)

James T
James T

Reputation: 627

You're missing the $ character at the end of your regular expression. The $ character matches the end of the string or line. Currently, it is checking if the string begins with zero or more hexadecimal strings of the specified length. Any string will begin with at least 0 instances of the string, so all strings are currently matching.

The regular expression should look like ^(((\s*0[xX]([0-9a-fA-F]{2}))\s*)*)$.

Alternatively, if you want it to begin with at least one of those hexadecimal strings, you should replace the last * character with a +, which will match one or more instances.

That regular expression would look like ^(((\s*0[xX]([0-9a-fA-F]{2}))\s*)+)$.

Lastly, if you want the strings to be separated by spaces, you would need to modify it a bit more. Both of those regular expressions will allow consecutive strings without spaces in between. I have a feeling that the 'correct' regular expression is going to be rather ugly, so you may be better off using String.Split on spaces and ignoring empty lines, running the regular expression ^0[xX]([0-9a-fA-F]{2})$ on each string.

Upvotes: 4

FishBasketGordo
FishBasketGordo

Reputation: 23142

You should end the regex with a $. Without that, it will match the number before the comma and return true. Should be like this:

^(((\s*0[xX]([0-9a-fA-F]{2}))\s*)*)$

If you don't want to match blank lines, change the final * to a +:

^(((\s*0[xX]([0-9a-fA-F]{2}))\s*)+)$

Also, if you're not using the groups you can drop the most of the parentheses:

^(\s*0[xX][0-9a-fA-F]{2}\s*)+$

Upvotes: 1

Related Questions