"JAVA", "ReplaceAll", "cheat"

Source: Internet
Author: User

There is a method in the Java string class called: ReplaceAll, on the surface, he means to replace all the regex with replacement.

1      Public string ReplaceAll (string regex, string replacement) {2         return Pattern.compile (regex). Matcher (this). ReplaceAll (replacement); 3     }

But in fact, it does not:

1      Public Static void Main (string[] args) {2         String str= "AAA"; 3         System.out.println (Str.replaceall ("AA", "a")); 4     }

The result is:

Aa

So, this method is deceptive.

The real replaceall should be this:

1  void replaceall (String str, string regex, string replacement) {2         if (Str.contains (regex)) {3             str = Str.replaceall (regex, replacement); 4             replaceall (str, regex, replacement); 5         Else {6            System.out.println (str); 7         }8     }

Test.java

1  Public classTest {2 3      Public Static voidMain (string[] args) {4String str = "AAATTAAAA";5String regex = "AA";6String replacement = "a";7 ReplaceAll (str, regex, replacement);8     }9 Ten      Public Static voidreplaceall (String str, string regex, string replacement) { One         if(Str.contains (regex)) { Astr =Str.replaceall (regex, replacement); - ReplaceAll (str, regex, replacement); -}Else { the System.out.println (str); -         } -     } -}

Output:

Atta

Tool

     Public Static string ReplaceAll (String str, string regex, string replacement) {        if  (Str.contains (regex)) { c7/>= str.replaceall (regex, replacement);            str=replaceall (str, regex, replacement);        }         return str;    }

Purely entertaining:)

"JAVA", "ReplaceAll", "cheat"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.