Pattern.matches() against a char array without cast to String in java

humbleDev :

Scenario

I need to check a regex pattern against a character array (char[]). I am not allowed to cast the character array to a String, because of security considerations. Java's Pattern.matches() method is designed to take a pattern and a String. Also, the regex pattern is passed to me from another source, and will change (is not constant).

This does not work:

// This pattern comes from another source, that I do not control. It may change.
String pattern = "^(.)\\1+$"; 

char[] exampleArray = new char[4];
    exampleArray[0] = 'b';
    exampleArray[1] = 'l';
    exampleArray[2] = 'a';
    exampleArray[3] = 'h';

// This should return true, for this pattern, but I cannot pass in a char[].
boolean matches = Pattern.matches(pattern, exampleArray); 

Thoughts

I attempted to deconstruct the regex pattern and examine the array for each part of the pattern, but the conditional logic required to interpret each part of the pattern thwarted me. For example: Suppose the pattern contains something like "(.){5,10}". Then I only need to check the char[] length. However, if it contains "^B(.){5,10}X", then I need to do something very different. It feels like there are too many possibilities to effectively deconstruct the regex pattern and account for each possibility (which is exactly why I've always just used Pattern.matches()).

Question

What would be the most efficient way of checking a regex pattern against a character array without casting the character array to a String, or creating a String?

Joni :

Pattern.matches accepts a general CharSequence. You can use for example CharBuffer from java.nio instead of String.

boolean matches = Pattern.matches(pattern, CharBuffer.wrap(exampleArray));

CharBuffer.wrap will not create an extra copy of the password in memory, so of all the options it's the safest.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=394429&siteId=1