This Java program reads an input text file and identifies valid email IDs using regular expressions. It forms a pattern for email IDs and checks each string in the file against this pattern. When a match occurs, the program writes the email ID to an output file. By leveraging regular expressions, developers can efficiently extract email addresses from text files, making it a useful tool for data processing and validation.
code:
import java.io.*; import java.util.regex.*; public class EmailExtractor { public static void main(String[] args) throws IOException { // Regular expression for email ID Pattern emailPattern = Pattern.compile("[a-zA-Z0-9][a-zA-Z0-9_.]*@[a-zA-Z0-9]+([.][a-zA-Z]+)+"); // Read input.txt file BufferedReader reader = new BufferedReader(new FileReader("input.txt")); String line; while ((line = reader.readLine()) != null) { Matcher matcher = emailPattern.matcher(line); while (matcher.find()) { System.out.println(matcher.group()); } } reader.close(); } }
Output:
[email protected] [email protected]
To run the Java program that detects email IDs in a text file, follow these steps:
1.Compile the Java File:
-
- Open your terminal or command prompt.
- Navigate to the directory containing your Java file (let’s assume it’s named
EmailExtractor.java
). - Compile the Java file using the command
-
javac EmailExtractor.java
2.Create an Input File
-
-
- Create a text file named “input.txt” (or use an existing one) in the same directory
- Add some text content with email addresses (valid or invalid)
-
3.Run the Program:
-
-
-
- Execute the compiled Java program using the command
-
java EmailExtractor
-
-