Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

c# - Check if string is valid represantion of HEX number

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

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

1 Reply

0 votes
by (71.8m points)

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.")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...