Hello all,

I am having some trouble I hope you can help me out with. I am trying to input a list of text, which has the name of a sub, the hull number, and the homeport of the sub, like this:

USS West Virginia [SSBN-736] Kings Bay, Georgia

a bunch of those lines. I am having trouble on how to break up the individual pieces of the lines of the text. Sometimes it is USS West Virginia, sometimes USS Indiana, and then sometimes the homeport will be Pearl Harbor, but others Kings Bay, Georgia. so the way I have used with the delimiter " " does not always work for everything. Can anything suggest what I could do to make this work all the time? the hull number will always have [] around the name if that helps....

this is what I have so far but it does not work for me:

try{
                
                while(fileInput.ready()){
                    
                    tempString = fileInput.readLine();
                    Scanner scanner = new Scanner(tempString);
                    scanner.useDelimiter(" ");
                    
                    if(scanner.hasNext()){
                        
                        StringBuffer subName = new StringBuffer("");
                        StringBuffer homePort = new StringBuffer("");
                        
                        subName.append(scanner.next()).append(" ");
                        subName.append(scanner.next());
                        
                        String hullNumber = scanner.next();
                        
                        homePort.append(scanner.next()).append(" ");
                        homePort.append(scanner.next());

"\\s+"

Read the API docs for Pattern and Matcher, the String functions work the same way (and, although I haven't checked that they do, they probably use those behind the scenes).

Don't use Scanner to process the input; just use it to read entire lines and process them in a separate function. That way, most of the program complexity would be abstracted in a separate function and if the delimiters or the parsing logic changes in future, all you would need to do would be make changes to the processing function and nothing else.

Using this method, you won't need to use Regular Expressions; just running a simple loop over the entire string would get the job done swift and simple.

This article has been dead for over six months. Start a new discussion instead.