- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to print all the strings that match a given pattern from a file in Java
Problem Description
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 newfile {
public static void main(String[] args) throws IOException {
Pattern p1 = Pattern.compile("[A-Za-z][a-z]+");
BufferedReader r = new BufferedReader(new FileReader("os.java"));
String line;
while ((line = r.readLine()) != null) {
Matcher m = p1.matcher(line);
while (m.find()) {
System.out.println(m.group(0));
int s1 = m.start(0);
int e1 = m.end(0);
System.out.println(line.substring(s1, e1));
}
}
}
}
Result
The above code sample will produce the following result.
Android java ios linux
java_regular_exp.htm
Advertisements