The first thing you can do to improve your code is move the logic outside of the main method. The section of your code where the string is scrubbed can be moved into a static method that takes two strings, a source string and list of characters to be removed, then returns the scrubbed String. Notice that the method returns a String rather than printing it; this is because it is good practice to keep I/O and program logic separate.
public static String removeCharacters(String sourceString,String characters){ String pat="([^"+characters+"])"; Pattern p=Pattern.compile(pat); Matcher m=p.matcher(sourceString); StringBuilder scrubbedBuilder = new StringBuilder(); while(m.find()){ scrubbedBuilder.append(m.group(0))); } return scrubbedBuilder.toString(); }
Now that the removeCharacters
logic has been abstracted from the main method, it's much simpler to modify it's implementation without worrying about how it will effect the rest of the code.
public static String removeCharacters(String sourceString,String characters){ String regex = "["+characters+"]"; return sourceString.replaceAll(regex,""); }
This code is almost exactly the same as the code you provided except a built in method of the String class is being used instead of manually managing the regex.
Finally, the main method needs to be modified to accommodate the abstraction of the removeCharacters
method. At the same time it can be modified to utilize Java7's try-with-resource and a few variables can be given more specific names.
public static void main(String[] args) { String filePath = args[0]; File file = new File(filePath); try(BufferedReader br = new BufferedReader(new FileReader(file));){ String inputLine; while ((inputLine = br.readLine()) != null) { inputLine = inputLine.trim(); String[] splitInput=inputLine.split(",\\s"); System.out.println(removeCharacters(splitInput[0],splitInput[1])); } } catch (IOException ioe){ System.err.println("Error occurred while attempting to read file " + filePath); } }
Here's the final version of the code.
import java.io.BufferedReader; import java.io.FileReader; import java.io.File; import java.io.IOException; public class Remove{ public static String removeCharacters(String sourceString,String characters){ String regex = "["+characters+"]"; return sourceString.replaceAll(regex,""); } public static void main(String[] args) { String filePath = args[0]; File file = new File(filePath); try(BufferedReader br = new BufferedReader(new FileReader(file));){ String inputLine; while ((inputLine = br.readLine()) != null) { inputLine = inputLine.trim(); String[] splitInput=inputLine.split(",\\s"); System.out.println(removeCharacters(splitInput[0],splitInput[1])); } } catch (IOException ioe){ System.err.println("Error occurred while attempting to read file " + filePath); } } }
The only other changes here are the name of the class and the imports. Instead of Main
the class is named Remove
and I've explicitly listed all the imported classes.