FullStack
FullStack

Reputation: 665

How to check blob input string is hex in java?

In our product, in a java class we are receiving Blob in string format and we need to check whether this incoming blob is a hex string (Blob can be of any size) and based on the boolean result we will decide further Blob processing(because in our case MS-SQL is returning Hex and MySQL,Oracle are returning pure Blob). Is it good practice to use Pattern, Matcher and matches() to check whether this incoming Blob is hex string ?

Following is my code snippet :

public static boolean isHexadecimal(String blobdata) {

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

    if (m.matches()) {
        return true;
    }
    return false;
}

Upvotes: 0

Views: 370

Answers (2)

dmolony
dmolony

Reputation: 1135

Here is some sample code

public class HexTester
{
  private static Pattern pattern = Pattern.compile ("^[0-9a-fA-F]+$");

  public static void main (String[] args)
  {
    System.out.println (isHexadecimal ("0102"));
    System.out.println (isHexadecimal ("xx0102"));
    System.out.println (isHexadecimal ("deadbeef"));
    System.out.println (isHexadecimal ("xxdeadbeef"));
  }

  private static boolean isHexadecimal (String blobdata)
  {
    Matcher m = pattern.matcher (blobdata);
    return m.matches ();
  }
}

Your regex would return true if it found any hex characters, this one checks that the entire string is valid hexadecimal.

Also, the pattern should only be compiled once, not every time you call the function.

If you want to be sure that the hex digits always come in pairs, you could use this

private static Pattern pattern = Pattern.compile ("^(?:[0-9a-fA-F]{2})+$");

Upvotes: 0

collapsar
collapsar

Reputation: 17238

The regex sports a deficiency insofar as it only flags that your blobdata contains a substring in hexadecimal ( not even taking into account that the number of consecutive hex bytes must be even if it represents an octet sequence ). Use start/end anchors to rectify that:

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

An alternative might be to invert the matching ruling out the occurrence of non-hex data in your blob. Of course, this is only viable if you are indeed after hex-only content:

public static boolean isHexadecimal(String blobdata) {

    Pattern p = Pattern.compile("[^0-9a-fA-F]");
    Matcher m = p.matcher(blobdata);

    if (m.matches()) {
        return false;
    }
    return true;
}

Upvotes: 1

Related Questions