user1703055
user1703055

Reputation: 149

What's the principle of 'replaceAll' method?

String s="a";
System.out.println(s.replaceAll(".*","1"));

Why the output of the code above is "11", not "1"?

Upvotes: 2

Views: 67

Answers (3)

Sumeet Sharma
Sumeet Sharma

Reputation: 2583

What exactly is happening is that when you dont mention any position of a. It checks before and after for zero occurrences. Hence two 1's get replaced. But if you provide a position for a. Say the first case then there is only one time that there is zero occurrence before a hence only one time the 1 gets printed

        String s="a";
        System.out.println(s.replaceAll(".*a","1")); // prints 1
        System.out.println(s.replaceAll(".*","1"));  //prints 11
        System.out.println(s.replaceAll("a.*","1"));  //prints 1

The * is for zero or more occurences of preceding text and . is for a wildcard character.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

Because of * which matches a charcter zero or more times. Use + instead you should see the difference .

Upvotes: 2

asontu
asontu

Reputation: 4659

Because .* matches Zero length matches

Change to .+ and you're good.

Upvotes: 2

Related Questions