验证字符串是否为十六进制 [英] Verify if String is hexadecimal
问题描述
我有一个类似09a的字符串,我需要一种方法来确认文本是否为十六进制。我发布的代码做了类似的事情,它验证了一个字符串是十进制数。
$ b
I have a String like "09a" and I need a method to confirm if the text is hexadecimal. The code I've posted does something similar, it verifies that a string is a decimal number. I want to do the same, but for hexadecimal.
private static boolean isNumeric(String cadena) {
try {
Long.parseLong(cadena);
return true;
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Uno de los números, excede su capacidad.");
return false;
}
}
推荐答案
超载 Long.parseLong
接受第二个参数,指定基数:
There's an overloaded Long.parseLong
that accepts a second parameter, specifying the radix:
Long.parseLong(cadena,16);
也可以迭代字符串中的字符并调用 Character.digit( c,16)
(如果它们中的任何一个返回 -1
,它不是有效的十六进制数字)。如果字符串太大而无法放入 long
中(如注释中指出的那样,如果使用第一种方法会导致异常),这是特别有用的。示例:
As an alternative, you could iterate over the characters in the string and call Character.digit(c,16)
on them (if any of them return -1
it's not a valid hexadecimal digit). This is especially useful if the string is too large to fit in a long
(as pointed out in the comments, that would cause an exception if the first method is used). Example:
private static boolean isNumeric(String cadena) {
if ( cadena.length() == 0 ||
(cadena.charAt(0) != '-' && Character.digit(cadena.charAt(0), 16) == -1))
return false;
if ( cadena.length() == 1 && cadena.charAt(0) == '-' )
return false;
for ( int i = 1 ; i < cadena.length() ; i++ )
if ( Character.digit(cadena.charAt(i), 16) == -1 )
return false;
return true;
}
顺便说一句,我建议分隔测试有效数字和向用户显示消息,这就是为什么我只是在上面的例子中返回 false
而不是首先通知用户的原因。
BTW, I'd suggest separating the concerns of "testing for a valid number" and "displaying a message to the user", that's why I simply returned false
in the example above instead of notifying the user first.
最后,您可以简单地使用正则表达式:
Finally, you could simply use a regular expression:
cadena.matches("-?[0-9a-fA-F]+");
这篇关于验证字符串是否为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!