How to search for a string in a file using Java regular expression.

If you need to search for a phrase or a string in a text file Java regular expression is the easiest way to accomplish this task. Here is a simple example that demonstrates how you can use Java regular expression to find a string or a phrase in a text file.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.ArrayList;
public class TextSearch{
	public ArrayList searchString(String fileName, 
                                            String phrase) throws IOException{
	  Scanner fileScanner = new Scanner(new File(fileName));
	  int lineID = 0;
	  ArrayList lineNumbers = new ArrayList();
	  Pattern pattern =  Pattern.compile(phrase);//,Pattern.CASE_INSENSITIVE);
	  Matcher matcher = null;
			String line = fileScanner.nextLine();
			matcher = pattern.matcher(line);

		return lineNumbers;

Here in this example I read input file line by line searching for the given string or phrase. The code uses Pattern and Matcher classes to search for the string. If a line contains the string we are looking for we store its line number in an ArrayList. At the end, the method returns the ArrayList of Integer objects depicting the lines of the file that have the given string. If the file does not contain given string an appropriate message will be printed.

Comments 5

Leave a Reply

Your email address will not be published. Required fields are marked *