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.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.*; import java.io.IOException; public class TextSearch{ public List searchString(String fileName, String phrase) throws IOException{ Scanner fileScanner = new Scanner(new File(fileName)); int lineID = 0; List lineNumbers = new ArrayList(); Pattern pattern = Pattern.compile(phrase); Matcher matcher = null; while(fileScanner.hasNextLine()){ String line = fileScanner.nextLine(); lineID++; matcher = pattern.matcher(line); if(matcher.find()){ lineNumbers.add(lineID); } } 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 a List. At the end, the method returns the List 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.
Nuebee
August 12, 2009 @ 9:55 pm
thanks for easy to follow tip.
patnaik
September 29, 2010 @ 11:24 pm
Very good and helpful tips….
Thanks …..
Mukesh
December 29, 2010 @ 3:44 am
Its very useful
krish
January 31, 2012 @ 2:10 am
input is String sub = “adsfasdf”
+ “adfereresdfadsfasdf”
+ “adfereresdfadsfasdfadfereresdf”;
required output is
img src=”uploadedfiles/sdf.png
img src=”uploadedfiles/asd1212wqdswsddf.png
img src=”uploadedfiles/asdfasd323f.png”>adfereresdf
megan
April 1, 2012 @ 9:23 pm
Thank you very much.
It helps a lot 🙂
celia
June 6, 2017 @ 11:16 am
Hello, how to use regular expressions to search for an uninitialized word, for example I want to program a function that reads the text of a json file and then searches for a term i and at the end give the number of lines that contain that term