public class FileParser {
private String filename = "mydata.txt";
private Pattern pattern = Pattern.compile("\\D\\D\\d+");
private Scanner reader;
public FileParser() throws FileNotFoundException{
reader = new Scanner(new File(filename));
}
public boolean hasMoreData(){
return reader.hasNext(pattern);
}
public String[] getNextData(){
return pattern.split(reader.next(pattern));
}
public void close(){
reader.close();
}
}
So this is my code. I am trying to take out a pattern that consists of 2 letters and a number. Why am I getting nothing/ an empty array from the getNextData() function?
Scanner.hasNext(pattern)searches for the pattern that starts between the delimiter. In your case, the delimiter is a|. But Scanner’s default delimiter is whitespace. You have to either manually change your delimiter to be a|or ignore the delimiter altogether. Here’s an example usingScanner.findWithinHorizon, which does not care about the delimiter: