I'm reading in a text file and want to parse based on labels within the text file. At first I was trying to do this with patterns, but after spending some time reading the API documents, I'm not sure what I need.

I think I'm making this too complicated.

Example of .txt file:

Title: Grapes of Wrath
descriptions
Title: Almost Transparent Blue
more descriptions

I only want to capture text between Title: and \n

My code that doesn't work (nor should it) looks like this:

String[] lines = loadStrings("books.txt");
  String bigstring = join(lines, " ");
  String regex = "Title: ";

   Pattern pattern = Pattern.compile(regex);
   String[] items = pattern.split(bigstring);
   for(int i=0; i < items.length; i++){
   println(items[i] + "\n");}

Your regex isn't complicated enough. The first part is correct (although I'd wrap it in parenthesis), but you need a mechanism to read in the text after the word 'Title:' which can be accomplished by saying (.*) and you also need to make sure the (.*) doesn't read in the newline which I'm pretty sure (but not positive) can be done by altering it to "(.*)?(\n)". You might also need a double backslash instead of the single one as an escape character, but I don't really remember.

Those are all guesses but to the best of my knowledge they are correct; I have worked with regexes somewhat in the past but I admit I tend to forget things and look them up. Give it a try and experiment a little.

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