35

「09a」のような文字列があり、テキストが 16 進数かどうかを確認する方法が必要です。私が投稿したコードも同様のことを行い、文字列が 10 進数であることを確認します。同じことをしたいのですが、16進数です。

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

8 に答える 8

34

Long.parseLong基数を指定して、2 番目のパラメーターを受け入れるオーバーロードがあります。

Long.parseLong(cadena,16);

別の方法として、文字列内の文字を繰り返し処理して呼び出すこともできCharacter.digit(c,16)ます (いずれかが返された場合、-1それは有効な 16 進数ではありません)。これは、文字列が大きすぎて a に収まらない場合に特に便利ですlong(コメントで指摘されているように、最初のメソッドが使用されると例外が発生します)。例:

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]+");
于 2012-07-11T02:05:57.710 に答える
32

例外の恐ろしい乱用。これは絶対にしないでください!(これは私ではなく、Josh Bloch の効果的な Java です)。とにかく、私は提案します

private static final Pattern HEXADECIMAL_PATTERN = Pattern.compile("\\p{XDigit}+");

private boolean isHexadecimal(String input) {
    final Matcher matcher = HEXADECIMAL_PATTERN.matcher(input);
    return matcher.matches();
}
于 2012-12-02T08:05:09.180 に答える
10

Long.parseLong には、2 番目の引数として基数を取る 2 番目の形式があります。

private static boolean isHexNumber (String cadena) {
  try {
    Long.parseLong(cadena, 16);
    return true;
  }
  catch (NumberFormatException ex) {
    // Error handling code...
    return false;
  }
}
于 2012-07-11T02:54:29.420 に答える
10

さまざまなオプションと実行時間の結果 (JDK 11) のコードを次に示します。

execution time isHex1: 3670 ms
execution time isHex2: 3294 ms
execution time isHex3: 3946 ms
execution time regex: 31288 ms

テストコード:

public class HexPerformanceTest {
    @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);

        Predicate<String> isHex1Test = testString -> {
            boolean isHex = true;
            for (char c: testString.toCharArray()) {
                if (!isHex1(c)) {
                    isHex = false;
                    break;
                }
            }
            return isHex;
        };

        Predicate<String> isHex2Test = testString -> {
            boolean isHex = true;
            for (char c: testString.toCharArray()) {
                if (!isHex2(c)) {
                    isHex = false;
                    break;
                }
            }
            return isHex;
        };

        Predicate<String> isHex3Test = testString -> {
            boolean isHex = true;
            for (char c: testString.toCharArray()) {
                if (!isHex3(c)) {
                    isHex = false;
                    break;
                }
            }
            return isHex;
        };

        Pattern pattern = Pattern.compile("^[0-9a-fA-F]+$");
        Predicate<String> regexTest = testString -> {
            Matcher matcher = pattern.matcher(regexString);
            return matcher.matches();
        };

        System.out.println("execution time isHex1: " + milliseconds(regexString, isHex1Test, count) + " ms");
        System.out.println("execution time isHex2: " + milliseconds(regexString, isHex2Test, count) + " ms");
        System.out.println("execution time isHex3: " + milliseconds(regexString, isHex3Test, count) + " ms");
        System.out.println("execution time regex: " + milliseconds(regexString, regexTest, count) + " ms");
    }

    private long milliseconds(String testString, Predicate<String> hexTest, int count) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            hexTest.test(testString);
        }
        return 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);
    }
}
于 2017-03-23T14:24:41.027 に答える
0

以下の方法で実質的に任意の長さのテキストをチェックできます。

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;
}
于 2012-07-11T09:37:16.027 に答える
0

これを試して。

static boolean isHexadecimal(String s) {
    return s.chars()
        .skip(s.startsWith("-") ? 1 : 0)
        .allMatch(c -> "0123456789ABCDEFabcdef".indexOf(c) >= 0);
}

public static void main(String[] args) {
    System.out.println(isHexadecimal("-0e34a29Fb"));
    System.out.println(isHexadecimal("-ff-"));
    System.out.println(isHexadecimal("ef-"));
    System.out.println(isHexadecimal("efg"));
}

出力:

true
false
false
false

.skip(s.startsWith("-") ? 1 : 0)記号を許可しない場合は省略できます。

于 2021-12-10T15:04:46.180 に答える