Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am total noob regarding regex. My goal is to check wether a string is a valid represantion of a HEX number. Currently my implementation (which I find really un-efficient) is having a List with all HEX digits (0,1,...9,A,B..F) and check wether my string contains chars not contained in given List. I bet this can be easily done using regular expressions but I have no Idea how to implement it.

 private bool ISValidHEX(string s)
       {
           List<string> ToCheck = new List<string>();
           for (int i = 0; i < 10; i++)
           {
               ToCheck.Add(i.ToString());
           }
           ToCheck.Add("A");
           ToCheck.Add("B");
           ToCheck.Add("C");
           ToCheck.Add("D");
           ToCheck.Add("E");
           ToCheck.Add("F");
           for (int i = 0; i < s.Length; i++)
           {
               if( !ToCheck.Contains(s.Substring(i,1)))
               {
                   return false;
               }
           }
           return true;
       }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
145 views
Welcome To Ask or Share your Answers For Others

1 Answer

I would have thought that it's quickest to attempt to convert your string to an integral type and deal with any exception. Use code like this:

int num = Int32.Parse(s, System.Globalization.NumberStyles.HexNumber);

The resulting code is possibly easier to follow than a regular expression and is particularly useful if you need the parsed value (else you could use Int32.TryParse which is adequately documented in other answers).

(One of my favourite quotations is by Jamie Zawinski: "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems.")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...