Search code examples
javaregexstringcompilationreplaceall

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?


Solution

  • Because of the first line, output is basically the equivalent of

    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(""). 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.