[英]Pattern.matches() against a char array without cast to String in java
我需要根據字符數組( char[]
)檢查正則表達式模式。 出於安全考慮,我不允許將字符數組轉換為字符串。 Java 的 Pattern.matches() 方法旨在接受一個模式和一個字符串。 此外,正則表達式模式是從另一個來源傳遞給我的,並且會發生變化(不是恆定的)。
這不起作用:
// 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);
我試圖解構正則表達式模式並檢查模式每個部分的數組,但解釋模式每個部分所需的條件邏輯讓我感到沮喪。 例如:假設模式包含類似"(.){5,10}"
。 然后我只需要檢查char[]
長度。 但是,如果它包含"^B(.){5,10}X"
,那么我需要做一些非常不同的事情。 感覺有太多的可能性可以有效地解構正則表達式模式並解釋每種可能性(這正是我一直只使用Pattern.matches()
)。
在不將字符數組轉換為字符串或創建字符串的情況下,根據字符數組檢查正則表達式模式的最有效方法是什么?
Pattern.matches 接受一個通用的 CharSequence。 例如,您可以使用 java.nio 中的 CharBuffer 而不是 String。
boolean matches = Pattern.matches(pattern, CharBuffer.wrap(exampleArray));
CharBuffer.wrap 不會在內存中創建額外的密碼副本,因此在所有選項中它是最安全的。
如果有人可以訪問機器的內存,那么問題可能遠遠超出密碼的發現。
boolean matches = Pattern.matches(pattern, new String(exampleArray));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.