简体   繁体   English

Pattern.matches() 针对 char 数组而不在 java 中强制转换为 String

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

Scenario设想

I need to check a regex pattern against a character array ( char[] ).我需要根据字符数组( 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. Java 的 Pattern.matches() 方法旨在接受一个模式和一个字符串。 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}" .例如:假设模式包含类似"(.){5,10}" Then I only need to check the char[] length.然后我只需要检查char[]长度。 However, if it contains "^B(.){5,10}X" , then I need to do something very different.但是,如果它包含"^B(.){5,10}X" ,那么我需要做一些非常不同的事情。 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() ).感觉有太多的可能性可以有效地解构正则表达式模式并解释每种可能性(这正是我一直只使用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?在不将字符数组转换为字符串或创建字符串的情况下,根据字符数组检查正则表达式模式的最有效方法是什么?

Pattern.matches accepts a general CharSequence. Pattern.matches 接受一个通用的 CharSequence。 You can use for example CharBuffer from java.nio instead of String.例如,您可以使用 java.nio 中的 CharBuffer 而不是 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. CharBuffer.wrap 不会在内存中创建额外的密码副本,因此在所有选项中它是最安全的。

如果有人可以访问机器的内存,那么问题可能远远超出密码的发现。

boolean matches = Pattern.matches(pattern, new String(exampleArray));

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

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