Reputation: 67
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?
Upvotes: 3
Views: 10665
Reputation: 4076
You can use a switch expression:
public static boolean isHex(final String str) {
return str != null &&
!str.isEmpty() &&
str.codePoints()
.allMatch((final int codePoint) -> switch (codePoint) {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F',
'a', 'b', 'c', 'd', 'e', 'f' -> true;
default -> false;
});
}
This solution is more efficient than using a regular expression and it doesn't rely on a try catch.
Upvotes: 0
Reputation: 3374
If anyone reached this thread trying to avoid the following exception when parsing a Mongodb ObjectId:
java.lang.IllegalArgumentException: invalid hexadecimal representation of an ObjectId: [anInvalidId]
Then note this utility method offered by the mongo-java-driver library:
ObjectId.isValid(stringId)
Related thread:
How to determine if a string can be used as a MongoDB ObjectID?
Upvotes: 0
Reputation: 30136
Given String str
as your input string:
Option #1:
public static boolean isHex(String str)
{
try
{
int val = Integer.parseInt(str,16);
}
catch (Exception e)
{
return false;
}
return true;
}
Option #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;
}
Upvotes: 1
Reputation: 124225
If you want to check if string contains only 0-9, a-h or A-H you can try using
yourString.matches("[0-9a-fA-F]+");
To optimize it you can earlier create 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
m.reset(newString);
if (m.matches())
Upvotes: 3
Reputation: 4252
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.
Refer the documentation here
Upvotes: 4