Created
July 10, 2012 14:06
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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