如何更有效地在单个字符串上调用 replaceAll 两次

How can I more efficiently call replaceAll twice on a single string

我目前想在一行中完成所有这些:

String output = Pattern.compile("(\r|\n|\t)").matcher(obj).replaceAll("");
Pattern.compile("[^\p{Print}]").matcher(output).replaceAll(replacement);

但我无法执行以下操作:

Pattern.compile("(\r|\n|\t)").matcher(obj).replaceAll("").Pattern.compile("[^\p{Print}]").matcher(output).replaceAll(replacement);

如何让第二个正则表达式也同时编译?

因为第一行,output基本上等同于

Pattern.compile("(\r|\n|\t)").matcher(obj).replaceAll("")

因此,您可以将第二行中的变量output替换为Pattern.compile("(\r|\n|\t)").matcher(obj).replaceAll("")。然后该行将变为

Pattern.compile("[^\p{Print}]").matcher(Pattern.compile("(\r|\n|\t)").matcher(obj).replaceAll("")).replaceAll(replacement);

然而,这并没有真正提高性能,而且对可读性有负面影响。除非你有充分的理由,否则最好只使用前两行。

如果 "efficiency" 对您来说意味着 "less typing",那么方法 String.replaceAll("regex", "replacement") 可能适合您:

String output = obj.replaceAll("(\r|\n|\t)", "").replaceAll("[^\p{Print}]", replacement);

您失去了保留模式以供重用的能力,如果您不得不多次使用它实际上会更有效率。