-3

I want a regex in c# that validates the hexadecimal number between 0 to FE (i.e. 0 to 254 in decimal)(Case insensitive).

here user can enter the single digit number in two digit. For example number 9 as 09.

any help is appreciated.

Note: We don't need to validate '0x' here,just a range between 0 to FE.

Mahendra
  • 155
  • 3
  • 12
  • 5
    You want to use... *Regex*?? – Ian Feb 18 '16 at 13:22
  • Possible duplicate of [How to convert numbers between hexadecimal and decimal in C#?](http://stackoverflow.com/questions/74148/how-to-convert-numbers-between-hexadecimal-and-decimal-in-c) – zimdanen Feb 18 '16 at 13:22
  • Suggest you attempt to convert to an int (see above link) and check the link. Use TryParse, in case the string is incorrect. – zimdanen Feb 18 '16 at 13:24
  • I don't want to convert the string,I ant a regex pattern to validate the string. – Mahendra Feb 18 '16 at 13:25
  • 2
    @Mahendra But why? Typically, you would use `Parse` or `Convert` or `TryParse` - even just to validate. `Regex` is often "overkill" for most scenarios - it may even perform slower than, let say, `TryParse`. Anyway, if you really need things to check the `string` without actually converting the `string`, I once have such wish too. For some special case, it is indeed beneficial. Check this out: http://stackoverflow.com/questions/34392763/tryparse-without-actual-parsing-or-any-other-alternative-for-checking-text-forma perhaps you want to explain your context too... – Ian Feb 18 '16 at 13:31

3 Answers3

4

Try this

^(([fF][0-9a-eA-E])|([0-9a-eA-E]?[0-9a-fA-F]))$

Some explanations:

This regex contains 2 logical parts. First ([fF][0-9a-eA-E]) matches cases when number starts with "f" or "F", as per original criteria, in that case only 0-9 and A-E is available, to reject "FF". Second part ([0-9a-eA-E]?[0-9a-fA-F]) handles all other cases, first symbol is 0-9 or A-E (F is covered by first part) or absent (to cover single symbol numbers), and second symbol is any valid for hexdecimal (0-9 A-F).

Alex Kopachov
  • 723
  • 4
  • 9
0

You can use

^(?:[0-9a-eA-E]?[0-9a-fA-F]|[fF][0-9a-eA-E])$

It will work with or without leading zero, uppercase or lowercase characters.

Explanation

Visualization

Gediminas Masaitis
  • 3,172
  • 14
  • 35
-1

Maybe this is what you want?

([0-9A-F]{1}[0-9A-E]{1})
kionay
  • 135
  • 4