The following are the necessary steps:
- Add the following import statements to the project:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
- Add the following declarations to the main method. The first is the text to be processed, and the second is a regular expression for an email address:
String sampleText = "I can normally be reached at [email protected]. " +
"If not you can email me at [email protected]";
String emailRegularExpression = "[a-zA-Z0-9'._%+-]+@" +
"(?:[a-zA-Z0-9-]+\.)" + "+[a-zA-Z]{2,4}";
- Insert the next sequence, which will create a pattern instance and a matcher instance for the regular expression:
Pattern pattern = Pattern.compile(emailRegularExpression);
Matcher matcher = pattern.matcher(sampleText);
- Add the following while loop, which finds occurrences of email addresses within the text and displays them:
while (matcher.find()) {
System.out.println(matcher.group());
}
- Execute the program. You will get the following output:
[email protected]
[email protected]