Skip to content

Instantly share code, notes, and snippets.

@vilmosioo
Created July 10, 2012 14:06
Show Gist options
  • Save vilmosioo/3083465 to your computer and use it in GitHub Desktop.
Save vilmosioo/3083465 to your computer and use it in GitHub Desktop.
How to properly scan a file for a specific regular expression, using Scanner and Pattern objects (Java code)
Scanner scanner = null;
try{
// change filePath to your your source
scanner = new Scanner(new BufferedReader(new FileReader(filePath)));
Pattern p = Pattern.compile("--REGEX--"); // enter your regular expression
while (scanner.hasNext()) {
Matcher m = p.matcher(scanner.nextLine());
while (m.find()) {
String result = m.group();
// do something with your result
}
}
} catch (Exception e) {
// Catch exception if any
System.err.println("Error: " + e.getMessage());
} finally {
if (scanner != null) {
scanner.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment