Reading a file and finding strings that match a particular pattern is a common file-handling task in Java. The java.io package can be used to read file contents, while the java.util.regex package helps search for matching strings.
- First, create and write content to a file.
- Then, read the file line by line and use a regular expression to find matching strings.
Steps to Print Strings That Match a Given Pattern
The process can be divided into two main steps:
Step 1: Create and Write to a File
The FileWriter class from the java.io package is used to create a file and write character data into it. The write() method adds the specified content to the file.
import java.io.FileWriter;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args)
{
try {
// Create a file and open it for writing
FileWriter writer = new FileWriter("test.txt");
// Write content into the file
writer.write("Hello Java Akshat 123\n");
writer.write("Learning Java Programming");
// Close the writer
writer.close();
System.out.println(
"Content written successfully.");
}
catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output
Content written successfully.
Explanation
- A FileWriter object is created with the file name test.txt.
- The write() method writes the specified text into the file.
- The \n character moves the content to the next line.
- The try-with-resources statement automatically closes the writer after the operation is completed.
- If an input/output error occurs, the catch block handles the IOException.
The program creates test.txt in the current working directory and writes the specified content into it.
Content of test.txt:
Hello Java Akshat 123
Learning Java Programming
Step 2: Read the File and Find Matching Strings
After creating the file, BufferedReader can be used to read its contents line by line. The Pattern and Matcher classes are then used to search for strings that match the specified regular expression.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchStringsFromFile {
public static void main(String[] args)
{
try {
// Create the file
FileWriter writer = new FileWriter("test.txt");
// Write content into the file
writer.write("Hello Java Akshat 123\n");
writer.write("Learning Java Programming");
writer.close();
System.out.println(
"Content written successfully.");
// Read the file
BufferedReader reader = new BufferedReader(
new FileReader("test.txt"));
// Define the pattern
Pattern pattern
= Pattern.compile("[A-Za-z][a-z]+");
System.out.println("\nMatched Strings:");
String line;
// Read the file line by line
while ((line = reader.readLine()) != null) {
// Search for the pattern
Matcher matcher = pattern.matcher(line);
// Print all matching strings
while (matcher.find()) {
System.out.println(matcher.group());
}
}
reader.close();
}
catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output
Content written successfully. Matched Strings: Hello Java Akshat Learning Java Programming
Explanation: The program first creates test.txt and writes two lines of text into it. BufferedReader then reads the file one line at a time, while Pattern defines the required regular expression. For every line, Matcher searches for matching strings. The find() method locates each occurrence, and group() returns the matched string, which is then printed.
Understanding the Regular Expression
The regular expression used in the example is:
[A-Za-z][a-z]+
This pattern matches a string that starts with an uppercase or lowercase English letter, followed by one or more lowercase English letters.
Part | Meaning |
|---|---|
[A-Z] | Matches one uppercase letter from A to Z. |
[a-z] | Matches one lowercase letter from a to z. |
[A-Za-z] | Matches one uppercase or lowercase English letter. |
+ | Matches one or more occurrences of the preceding pattern. |
[A-Za-z][a-z]+ | Matches a word beginning with a letter, followed by at least one lowercase letter. |
Example Matches
For the input:
Hello Java Akshat 123
Learning Java Programming
The regular expression matches:
Hello
Java
Akshat
Learning
Java
Programming
The number 123 is not matched because the pattern requires the first character to be an English letter.
Note: This pattern does not match every possible word. For example, it will not match A or JAVA because at least one lowercase letter must follow the first character.
Understanding Pattern and Matcher
The Pattern and Matcher classes are important components of Java's regular expression API.
Pattern Class
The Pattern class represents a compiled regular expression. It is used to define the pattern that the program wants to search for.
Syntax:
Pattern pattern = Pattern.compile("regex");
Example:
Pattern pattern = Pattern.compile("[A-Za-z][a-z]+");
Here, the regular expression is compiled into a Pattern object, which can be used to create matchers for different input strings.
Matcher Class
The Matcher class is used to perform matching operations on a character sequence using a compiled Pattern.
Syntax:
Matcher matcher = pattern.matcher(input);
Example:
Matcher matcher = pattern.matcher("Hello Java");
The Matcher object searches the given input for substrings that match the regular expression.