How to print all the strings that match a given pattern from a file?
Solution:
Following example shows how to print all the strings that match a given pattern from a file with the help of Patternname.matcher() method of Util.regex class.
import java.util.regex.*;
import java.io.*;
public class ReaderIter {
public static void main(String[] args)
throws IOException {
Pattern patt = Pattern.compile("[A-Za-z][a-z]+");
BufferedReader r = new BufferedReader
(new FileReader("ReaderIter.java"));
String line;
while ((line = r.readLine()) != null) {
Matcher m = patt.matcher(line);
while (m.find()) {
System.out.println(m.group(0));
int start = m.start(0);
int end = m.end(0);
Use CharacterIterator.substring(offset, end);
System.out.println(line.substring(start, end));
}
}
}
}
Result:
The above code sample will produce the following result.
Ian
Darwin
http
www
darwinsys
com
All
rights
reserved
Software
written
by
Ian
Darwin
and
others