Java Reference
In-Depth Information
a@k matches the regex .@.
webmaster@jdojo.com does not match the regex .@.
r@j matches the regex .@.
a%N does not match the regex .@.
.@. matches the regex .@.
Some important points to note are the following:
".@." did not match “ webmaster@jdojo.com ”, because a dot means
only one character and the String.matches() method matches the pattern in the regular
expression against the entire string. Note that the string "webmaster@jdojo.com" has the
pattern represented by .@. ; that is, a character followed by @ and another character. However,
the pattern matches part of the string, not the entire string. The "r@j" part of “ webmaster@
jdojo.com" matches that pattern. I will present some examples where you will match the
pattern anywhere in the string rather than match the entire string.
The regular expression
If you want to match a dot character in a string, you need to escape the dot in the regular
expression. The regular expression ".\\.." will match any string of three characters
in which the middle character is a dot character. For example, The method call "a.b".
matches(".\\..") will return true ; the method call "...".matches(".\\..") will return
true ; the method calls "abc".matches(".\\..") and "aa.ca".matches(".\\..") will return
false .
You can also replace the matching string with another string. The String class has two methods to do the match
replacement:
String replaceAll(String regex, String replacementString):
String replaceFirst(String regex, String replacementString):
The replaceAll() method replaces strings, which match the pattern represented by the specified regex , with the
specified replacementString . It returns the new string after replacement. Some examples of using the replaceAll()
method are as follows:
String regex = ".@.";
// newStr will contain "webmaste***dojo.com"
String newStr = "webmaster@jdojo.com".replaceAll(regex,"***");
// newStr will contain "***"
newStr = "A@B".replaceAll(regex,"***");
// newStr will contain "***and***"
newStr = "A@BandH@G".replaceAll(regex,"***");
// newStr will contain "B%T" (same as the original string)
newStr = "B%T".replaceAll(regex,"***");
 
Search WWH ::




Custom Search