"Hi, Amigo!"
"As far as I know, Rishi has already told you about regular expressions."
"Yes, it was very interesting."
"Great, now I'll tell you about using regular expressions to work with Strings."
"Let's start with the simplest question:"
1) How do I check to see if a String matches the pattern specified by a regular expression?
"There is a matches method for this. You pass a String containing a regular expression, and the method returns true or false."
Method(s) | Example(s) |
---|---|
|
|
Result:
|
2) How do I replace all matching substrings with different strings?
"There are two methods for this."
"The replaceAll method replaces all occurrences of a substring with another string."
"The replaceFirst method replaces the first occurrence of a passed substring with a specified string."
Method(s) | Example(s) |
---|---|
|
|
Result:
|
|
|
|
Result:
|
3) How do I split a string into parts?
"For this, we have the split method, which takes a delimiting mask:"
Method(s) | Example(s) |
---|---|
|
|
Result (an array of three strings):
|
"The StringTokenizer class is another way to split a string into parts."
"This class doesn't use regular expressions. Instead, you simply pass in a String containing a set of delimiters. The advantage of this approach is that it doesn't break the entire string into pieces all at once, instead it slowly moves from the beginning to the end."
"The class consists of a constructor and two methods. You need to pass the String we are breaking apart into the constructor, along with a String containing the set of delimiting characters."
The nextToken method returns the next token (substring).
The hasMoreTokens() method returns true if there are still substrings that haven't been returned yet.
Method(s) | Example(s) |
---|---|
|
|
Screen output:
|
"Note that any character in the second String passed to the StringTokenizer constructor is treated as a delimiter."
"Once again, everything seems clear. I might not be able to write this code all by myself right away, but I understand what's going on here."
"Excellent, then we'll assume that you've mastered the topic."
GO TO FULL VERSION