The differences between replace, ReplaceAll, and Replacefirst for Java strings

Source: Internet
Author: User
Tags first string

If not just review the next regular expression, I may also not notice that the original string replaceall and Replacefirst used the regular expression!

Not much to explain, look at the code:

1234 String s = "my.test.txt";System.out.println(s.replace(".""#"));System.out.println(s.replaceAll(".""#"));System.out.println(s.replaceFirst(".""#"));

Operation Result:

123 my#test#txt############y.test.txt

Does it feel magical?

Actually understand the regular expression should have been found, yes, "." is a meta-character of a regular expression that matches any character except newline characters, so replaceall and Replacefirst appear as such.

Replace does not use regular expressions, but it will put all "." Replaced, many people may misunderstand that replace is a replacement for a single, and ReplaceAll is a replacement for all, in fact this is wrong (I thought so before-). Replace simply does not use a regular expression, but replaces all matching strings.

Here some small partners who do not understand the regular expression may be shouting to the pit father, "then I do not want to use regular expression to replace the first string of swollen?" "It's also very simple, just escape the meta-string."

1 s.replaceFirst("\\.""#")

Operation Result:

1 my#test.txt

Here is a word list characters that will be recognized by the regular expression:

. match any character except line break

^ Start of matching string

$ match End of string

* Repeat 0 or more times

+ Repeat one or more times

? Repeat 0 or one time

Of course, the regular can be far more than that, personal advice to take some time to learn better ~

Add: The split of string is also used in regular expressions, use the time to pay attention to the point Oh!

The difference between replace replace, ReplaceAll, Replacefirst for Java strings

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.