简体   繁体   English

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

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

I currently want to do this all in one line: 我目前想一口气做这件事:

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

But I am unable to do the following: 但我无法执行以下操作:

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

How can I make it so that the second regex is also compiled at the same time? 如何使第二个正则表达式也同时编译?

If "efficiency" means "less typing" for you, then the method String.replaceAll("regex", "replacement") might be for you: 如果“效率”对您来说意味着“少打字”,那么String.replaceAll(“ regex”,“ replacement”)方法可能适合您:

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

You lose the ability to keep the Pattern for reuse, which would actually be more efficient if you have to use it more than once. 您将失去保留该模式以供重用的能力,如果您必须多次使用它,那么实际上会更有效率。

Because of the first line, output is basically the equivalent of 由于第一行, output基本上等于

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

Because of that, you can replace the variable output in the second line with Pattern.compile("(\\\\r|\\\\n|\\\\t)").matcher(obj).replaceAll("") . 因此,您可以将第二行中的变量output替换为Pattern.compile("(\\\\r|\\\\n|\\\\t)").matcher(obj).replaceAll("") Then the line would become 然后线会变成

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

However, this does not really improve performance, and has a negative impact on readability. 但是,这并不能真正提高性能,并且对可读性有负面影响。 Unless you have a really good reason, it would be best to just use the first two lines. 除非您有充分的理由,否则最好只使用前两行。

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

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