Java regex

Hey,

I am trying to read from a text file using JFileChooser and i need the reader.ReadLine to stop reading after a space has been found. So i am looking to regex to help me solve this issue. The text file i am trying to read from has just one word and after that a few numbers that have hints for guessing that word associated with them

lion 6 2 4 6 8 15 19
snake 7 3 5 7 8 12 21 23
crocodile 6 3 4 7 8 22 23
shark 5 1 5 7 8 11
giraffe 5 2 4 6 9 16
elephant 5 2 4 9 17 18
cheetah 6 2 4 6 8 13 14
whale 5 1 5 7 10 20

like so.

the method i have gotten so far is this
public static void getFile() throws Exception
{
JFileChooser fileChooser = new JFileChooser();

     java.io.File file = fileChooser.getSelectedFile();

      Scanner input = new Scanner(file);

     BufferedReader reader=new BufferedReader(new FileReader(file));//reads the file

     String ex = "[ ]";
      ArrayList<String> wordsIn=new ArrayList();
      while((lines = reader.readLine()) != null)
      { 
      wordsIn.add(lines);
      }

however im not sure how to make the while loop not pick up on the numbers as i dont want them to be in the final output for the Word guessing game

The while as it is reads the whole line. So lines contains the current line, if there is any, else it breaks the while.

If you can garantee that each line has a word and you only want to store the word you could use wordsIn.add(lines.split(" ")[0]).

If the goal is to also save and use the numbers later on, I could give suggestions later on. If you really want to use regex, take a look at https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html.

1 Like

is there a way to get just the numbers into a seperate ArrayList without the words?

You could simply use the already generated Array:
String[] splittt = lines.split(" ")
and then use elements 1 to (length-1) in a for loop with Integer.parseInt to generate an integer (or null if it aint one) from the rest of the line

see https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String) for more information

edit: You might want to use an ArrayList<ArrayList<Integer>> for that. or even better a Hashmap, where you use the word as a key (if you can guarantee that the words arr all unique)
or give them all an unique identifier (hence for simplicity I would use the current line number or something like that)

1 Like

Thanks For the help, I got the assignment done