Alex Thomson
Alex Thomson

Reputation: 143

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?

Upvotes: 0

Views: 1951

Answers (2)

sheltem
sheltem

Reputation: 3825

If "efficiency" means "less typing" for you, then the method String.replaceAll("regex", "replacement") might be for you:

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.

Upvotes: 3

The Guy with The Hat
The Guy with The Hat

Reputation: 11132

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.

Upvotes: 2

Related Questions