Created
March 12, 2016 04:34
-
-
Save martyychang/ff6af364d565b109d692 to your computer and use it in GitHub Desktop.
Java 7 script showing how a regex can be used to split strings delimited by backslash characters.
This file contains 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
package script; | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.nio.charset.Charset; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.regex.Pattern; | |
public class RegexScript { | |
public static final String INPUT_FILE = "sample.txt"; | |
public static final String SPLIT_REGEX = "\\s*,\\s*|\\\\|/"; | |
/** | |
* The script reads a file, line by line, and splits each line using | |
* a predefined regex. The results of the split are then displayed element | |
* by element for each line. | |
* | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
// Make sure the file exists! | |
Path inputFilePath = getInputFilePath(); | |
System.out.println("inputFilePath: " + inputFilePath.toAbsolutePath()); | |
assert(Files.exists(inputFilePath)); | |
// Read the file using a BufferedReader object | |
List<String> lines = null; | |
try { | |
Charset utf8 = Charset.forName("UTF-8"); | |
lines = Files.readAllLines(getInputFilePath(), utf8); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
// Make sure we read something! | |
assert(lines != null); | |
// For each read line, split the string by the regex | |
// and then display the results of the split. | |
for (String eachLine : lines) { | |
System.out.println("line: " + eachLine); | |
// Split the string. | |
String[] parts = eachLine.split(SPLIT_REGEX); | |
// Display the split parts | |
//System.out.println("line parts: " + parts); | |
System.out.println(Arrays.toString(parts)); | |
} | |
} | |
private static Path getInputFilePath() { | |
return Paths.get(INPUT_FILE); | |
} | |
} |
This file contains 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
The quick brown fox | |
jumped\over\the | |
lazy, crazy ,brown,sleeping , dog | |
who/was/eating/pastries |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment