RegEx for Hex string validation

  • Thread starter Thread starter slg
  • Start date Start date
S

slg

How can i validate the characters in a string are all hex chars.

I tried following but it does not work.

Regex r = new Regex(@"^([A-F]|[a-f]|[0-9])*");



TIA.
 
Hi,

what about trying to convert the hex into a e.g. long value?
When it fails you will get a exception and you can handle the
exception depending on the error.

Regards

Kerem

--
 
slg said:
How can i validate the characters in a string are all hex chars.

I tried following but it does not work.

Regex r = new Regex(@"^([A-F]|[a-f]|[0-9])*");

You've got the ^ at the beginning, but no $ at the end. You can also
express the middle part more simply:

Regex r = new Regex(@"^[A-Fa-f0-9]*$");

Note that it will match an empty string as well as one with actual
content - is that what you want?
 
thx alot

Yes, this is exactly what i was looking for.



Jon Skeet said:
slg said:
How can i validate the characters in a string are all hex chars.

I tried following but it does not work.

Regex r = new Regex(@"^([A-F]|[a-f]|[0-9])*");

You've got the ^ at the beginning, but no $ at the end. You can also
express the middle part more simply:

Regex r = new Regex(@"^[A-Fa-f0-9]*$");

Note that it will match an empty string as well as one with actual
content - is that what you want?
 
This one works fine to me.

"^([a-f|A-F|0-9]{2})+$"

This checks strings like

1) "1F5" - error ( must be % 2)
2) "G03" - error
3) "" - error
3) "01F5"- OK
How can i validate the characters in a string are all hex chars.

I tried following but it does not work.

Regex r = new Regex(@"^([A-F]|[a-f]|[0-9])*");



TIA.
On Saturday, December 01, 2007 12:23 PM Kerem Gümrükcü wrote:
Hi,

what about trying to convert the hex into a e.g. long value?
When it fails you will get a exception and you can handle the
exception depending on the error.

Regards

Kerem

--
-----------------------
Beste Grüsse / Best regards / Votre bien devoue
Kerem Gümrükcü
Microsoft Live Space: http://kerem-g.spaces.live.com/
Latest Open-Source Projects: http://entwicklung.junetz.de
On Saturday, December 01, 2007 1:44 PM Jon Skeet [C# MVP] wrote:

You've got the ^ at the beginning, but no $ at the end. You can also
express the middle part more simply:

Regex r = new Regex(@"^[A-Fa-f0-9]*$");

Note that it will match an empty string as well as one with actual
content - is that what you want?
 
Back
Top