"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)
boolean matches(String regex)
String s = "Good news, everyone!";
Boolean test = s.matches("news\\.*");
Result:

false (the String doesn't start with "news")

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)
String replaceAll(String regex, String replacement)
String s = "Good news, everyone!";
String s2 = s.replaceAll ("e\\.","EX");
Result:

s2 == "Good nEXs EXEXyonEX";
String replaceFirst(String regex, String replacement)
String s = "Good news, everyone!";
String s2 = s.replaceFirst("e\\.","EX");
Result:

s2 == "Good nEXs, everyone!";

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)
String[] split(String regex)
String s = "Good news everyone!";
String[] ss = s.split("ne");
System.out.println(Arrays.toString(ss));
Result (an array of three strings):

[Good , ws everyo, !]
"Good ", "ws everyo", "!";

"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)
boolean hasMoreTokens()

String nextToken()
String s = "Good news, everyone!";

StringTokenizer tokenizer =
new StringTokenizer(s,"ne");
while (tokenizer.hasMoreTokens())
{
String token = tokenizer.nextToken();
System.out.println(token);
}
Screen output:

Good
ws
v
ryo
!

"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."