检查字符串的十六进制数有效represantion [英] Check if string is valid represantion of HEX number

查看:185
本文介绍了检查字符串的十六进制数有效represantion的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我就总小白正则表达式
我的目标是请检查是否一个字符串是一个十六进制数的有效represantion。
目前我实现(我觉得这真的取消有效)正与所有十六进制数字列表(0,1,... 9,A,B..F),并请检查是否我的字符串中包含的字符不包含在给定的列表。
我敢打赌,这可以用正则表达式来容易做,但我不知道如何实现它。

 私人布尔ISValidHEX(字符串s)
{
名单,LT;字符串> ToCheck =新的List<串GT;();
的for(int i = 0;我小于10;我++)
{
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;我++)
{
如果
(ToCheck.Contains(s.Substring(I,1))!) {
返回false;
}
}
返回真;
}


解决方案

我本来认为它是最快尝试把字符串转换为整数类型及处理任何异常。使用这样的代码:

  INT NUM = Int32.Parse(S,System.Globalization.NumberStyles.HexNumber); 

生成的代码可能是容易按照比一个正则表达式,如果你需要的分析是非常有用的值(否则你可以使用 Int32.TryParse 这充分证明在其他的答案)。



(我的一个喜欢的名言是由Jamie Zawinski撰写:'我知道,我将使用正则表达式'。有些人,当遇到一个问题,认为现在他们有两个问题)


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;
       }

解决方案

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

这篇关于检查字符串的十六进制数有效represantion的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆