Which is more efficient: replaceFirst () or replaceAll () with a bound regular expression?

We have a line String s = "first.second.third...n-1.n";

Which of the two regex approaches is more efficient in Java?

s = s.replaceFirst(".*?\\.", "");

or

s = s.replaceAll('^[^.]+[.]', '');

They do the same, but I wonder which one is faster?

The differences are as follows:

  • using bound regular expression and replaceFirst()to match only the first instance

  • using non-greedy *?versus non-point character class[^.]

  • using the \\.literal vs. character class [.].

I would prefer an answer that evaluates or explains the performance effect of these separately.

+5
source share
1 answer

, .

, . ,

<.*?>

25 ,

<[^>]*>

, <0123456789>, , , .

\\. [.] - .

replaceAll , replaceFirst, , . . , + *.

replaceAll , , ( , ), , .

+4

All Articles