validationString是否为hex

我有一个类似“09a”的字符串,我需要一种方法来确认文本是否为hex。 我发布的代码做了类似的事情,它validation字符串是十进制数。 我想做同样的事情,但对于hex。

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接受第二个参数,指定基数:

 Long.parseLong(cadena,16); 

作为替代方案,您可以迭代字符串中的字符并在其上调用Character.digit(c,16) (如果它们中的任何一个返回-1则它不是有效的hex数字)。 如果字符串太大而不适合long (如注释中所指出的那样,如果使用第一种方法会导致exception),这将特别有用。 例:

 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而不是先通知用户。

最后,您可以简单地使用正则表达式:

 cadena.matches("-?[0-9a-fA-F]+"); 

可怕的滥用例外情况。 不要这样做! (这不是我,这是Josh Bloch的有效Java)。 无论如何,我建议

 boolean isNumeric = str.matches("\\p{XDigit}+"); 

在我自己的代码中使用它来检查字符串是否是MAC地址

 boolean isHex = mac_addr.matches("^[0-9a-fA-F]+$"); 

我对此线程中提供的其他答案的看法是,如果String的长度很大,它也会抛出exception。 因此,如果您正在测试MAC地址是否包含有效的hex数,则不是非常有用。

不要害怕使用正则表达式!

Long.parseLong有第二种forms,它将基数作为第二个参数。

 private static boolean isHexNumber (String cadena) { try { Long.parseLong(cadena, 16); return true; } catch (NumberFormatException ex) { // Error handling code... return false; } } 

这里有一些代码用于不同的选项和执行时间结果(JDK 8):

 execution time isHex1: 4540 execution time isHex2: 420 execution time isHex3: 7907 execution time regex: 46827 

测试代码:

 @Test public void testPerformance() { int count = 100000000; char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; String regexString = new String(chars); Pattern pattern = Pattern.compile("^[0-9a-fA-F]+$"); long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { for (char c: chars) { isHex1(c); } } System.out.println("execution time isHex1: " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { for (char c: chars) { isHex2(c); } } System.out.println("execution time isHex2: " + (System.currentTimeMillis() - start)); for (int i = 0; i < count; i++) { for (char c: chars) { isHex3(c); } } System.out.println("execution time isHex3: " + (System.currentTimeMillis() - start)); for (int i = 0; i < count; i++) { Matcher matcher = pattern.matcher(regexString); matcher.matches(); } System.out.println("execution time regex: " + (System.currentTimeMillis() - start)); } private boolean isHex1(char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } private boolean isHex2(char c) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': return true; default: return false; } } private boolean isHex3(char c) { return (Character.digit(c, 16) != -1); } 

没有图书馆的方法

 public static boolean isHexadecimal(String value) { if (value.startsWith("-")) { value = value.substring(1); } value = value.toLowerCase(); if (value.length() <= 2 || !value.startsWith("0x")) { return false; } for (int i = 2; i < value.length(); i++) { char c = value.charAt(i); if (!(c >= '0' && c <= '9' || c >= 'a' && c <= 'f')) { return false; } } return true; } 

您可以使用以下方法检查任何长度的文本。

 public static boolean isHexadecimal(String text) { Objects.requireNonNull(text); if(text.length() < 1) throw new IllegalArgumentException("Text cannot be empty."); char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F' }; for (char symbol : text.toCharArray()) { boolean found = false; for (char hexDigit : hexDigits) { if (symbol == hexDigit) { found = true; break; } } if(!found) return false; } return true; }