简体   繁体   English

检查十六进制字符串仅包含十六进制有界值

[英]check hex string contains only hex bounded values

How to check a given hex string contains only hex number.如何检查给定的十六进制字符串只包含十六进制数字。 is there is any simple method or any java library for the same?i have string like "01AF" and i have to check string only contains hex range values,for that what i am doing now is take the string and then split the string and then converted it to appropriate format then make a check for that value.is there is any simple method for that?是否有任何简单的方法或任何相同的 java 库?我有像“01AF”这样的字符串,我必须检查字符串只包含十六进制范围值,为此我现在正在做的是获取字符串然后拆分字符串和然后将其转换为适当的格式,然后检查该值。是否有任何简单的方法?

try
{
    String hex = "AAA"
    int value = Integer.parseInt(hex, 16);  
    System.out.println("valid hex);
 }
 catch(NumberFormatException nfe)
 {
    // not a valid hex
    System.out.println("not a valid hex);
 }

This will throw NumberFormatException if the hex string is invalid. 如果十六进制字符串无效,这将抛出NumberFormatException。

Refer the documentation here 请参阅此处的文档

If you want to check if string contains only 0-9, ah or AH you can try using 如果你想检查字符串是否只包含0-9,ah或AH,你可以尝试使用

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

To optimize it you can earlier create Pattern 要优化它,您可以更早创建Pattern

Pattern p = Pattern.compile("[0-9a-fA-F]+");

and later reuse it as 然后重复使用它

Matcher m = p.matcher(yourData);
if (m.matches())

and even reuse Matcher instance with 甚至重用Matcher实例

m.reset(newString);
if (m.matches())

Given String str as your input string: 给出String str作为输入字符串:

Option #1: 选项1:

public static boolean isHex(String str)
{
    try
    {
        int val = Integer.parseInt(str,16);
    }
    catch (Exception e)
    {
        return false;
    }
    return true;
}

Option #2: 选项#2:

private static boolean[] hash = new boolean[Character.MAX_VALUE];
static // Runs once
{
    for (int i=0; i<hash.length; i++)
        hash[i] = false;
    for (char c : "0123456789ABCDEFabcdef".toCharArray())
        hash[c] = true;
}
public static boolean isHex(String str)
{
    for (char c : str.toCharArray())
        if (!hash[c])
            return false;
    return true;
}

If anyone reached this thread trying to avoid the following exception when parsing a Mongodb ObjectId:如果有人在解析 Mongodb ObjectId 时尝试避免以下异常到达此线程:

java.lang.IllegalArgumentException: invalid hexadecimal representation of an ObjectId: [anInvalidId]

Then note this utility method offered by the mongo-java-driver library:然后注意 mongo-java-driver 库提供的这个实用方法

ObjectId.isValid(stringId)

Related thread:相关线程:

How to determine if a string can be used as a MongoDB ObjectID? 如何确定一个字符串是否可以用作 MongoDB ObjectID?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM