Scenario
我需要根据字符数组检查正则表达式模式(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);
Thoughts
我尝试解构正则表达式模式并检查模式每个部分的数组,但解释模式每个部分所需的条件逻辑阻碍了我。例如:假设模式包含类似的内容"(.){5,10}"
。然后我只需要检查char[]
长度。但是,如果它包含"^B(.){5,10}X"
,那么我需要做一些非常不同的事情。感觉有太多的可能性来有效地解构正则表达式模式并解释每种可能性(这正是我总是使用Pattern.matches()
).
Question
在不将字符数组转换为字符串或创建字符串的情况下,根据字符数组检查正则表达式模式的最有效方法是什么?
Pattern.matches 接受通用的 CharSequence。例如,您可以使用 java.nio 中的 CharBuffer 而不是 String。
boolean matches = Pattern.matches(pattern, CharBuffer.wrap(exampleArray));
CharBuffer.wrap 不会在内存中创建密码的额外副本,因此在所有选项中它是最安全的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)