How to do it...

The following are the necessary steps:

  1. Add the following import statements to the project:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  1. 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}";
  1. 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);
  1. 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());
}
  1. Execute the program. You will get the following output:
[email protected]
[email protected]

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.103.64