RegEx for Hex string validation

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.
 
K

Kerem Gümrükcü

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

--
 
J

Jon Skeet [C# MVP]

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?
 
S

slg

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?
 
A

Alexei Prokudin

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Difficulty with Regex pattern to validate a string 11
Regex in C# 4
regex replace question 1
RegEx Help!! 2
Regex Question 1
Regex woes 8
regex multiplication problem 3
Bug in Regex? 5

Top