基本上:如果有一个非正则表达式操作可以一步完成你想要的事情,那么请始终选择这种方法。
这与性能关系不大,而是与a)易读性和b)编译时安全性有关。专门的非正则表达式版本通常比正则表达式版本更容易阅读。在这些专门的方法中,一个打字错误将无法编译,而在正则表达式中,一个打字错误将在运行时失败。
比较基于正则表达式的解决方案和非基于正则表达式的解决方案
String s = "Magic_Carpet_Ride";
s.startsWith("Magic"); // non-regex
s.matches("Magic.*"); // regex
s.contains("Carpet"); // non-regex
s.matches(".*Carpet.*"); // regex
s.endsWith("Ride"); // non-regex
s.matches(".*Ride"); // regex
在这些情况下,使用非正则表达式版本是很明显的选择。
但当事情变得更加复杂时,就要看情况而定。我想我仍然会在以下情况下坚持使用非正则表达式,但许多人不会:
// Test whether a string ends with "magic" in any case,
// followed by optional white space
s.toLowerCase().trim().endsWith("magic"); // non-regex, 3 calls
s.matches(".*(?i:magic)\\s*"); // regex, 1 call, but ugly
针对 RegexesCanCertainlyBeEasierToReadThanMultipleFunctionCallsToDoTheSameThing
的回应:
我仍然认为非正则表达式版本更易读,但我会这样写:
s.toLowerCase()
.trim()
.endsWith("magic");
这可真是有很大的区别啊,不是吗?