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:
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