Presenting a text file as a single block in Java and matching strings in text

How can I get a text file (or XML file) represented as a whole string and search (or match) for a specific string in it?

I created a BufferedReader object:

BufferedReader input =  new BufferedReader(new FileReader(aFile));

      

and then I tried to use the Scanner class with its option to specify different delimiters like:

//Scanner scantext = new Scanner(input);
//Scanner scantext = new Scanner(input).useDelimiter("");
Scanner scantext = new Scanner(input).useDelimiter("\n");
while (scantext.hasNext()) {  ... }

      

Using the Scanner class like this I can either read the text line by line or word by word, but that doesn't help me because sometimes in the text I want to process I have

</review><review>

      

and I would like to say: if you find " <review>

" anywhere in the text, do something with the next next lines (or piece of text) until you find " </review>

". The problem is that <review>

both </review>

are located in different places in the text, and sometimes they are glued to other text (therefore, empty space as a separator does not help me).

I thought I could use the regex API in Java (Pattern and Matcher classes), but they seem to match a specific string or string, and I want the text to be as one continuous line (at least that was my impression of of what I read about them). Could you please tell me which structures / methods / classes I should be using in this case? Thanks.

+1


source to share


6 answers


Don't try to parse XML with regular expressions; it only leads to pain. There are many very nice present the XML the API in Java already; why try to invent them?

Anyway, to find a line in a text file, you must:



+3


source


It looks to me like you are trying to work with a structured XML file, and suggest that you take a look into javax.xml.parsers.DocumentBuilder or some other built-in API to parse the document.



+1


source


Use an XML parser.

Or use xpath like in this example .

+1


source


I thought I could use the regex API in Java (Pattern and Matcher classes), but they seem to match a specific string or string, and I want the text to be as one continuous line

Um, is something stopping you from reading an XML file into a String and then working with it using the regex API?

You can read the file into String easily using, for example, FileUtils from Apache Commons IO : see readFileToString(File file, String encoding)

.

+1


source


I would also recommend using XML parsing ... But since you only want to do something in the case of the "review" tag, perhaps you could use SAX better than the DOM ...

+1


source


I think here we can copy a single line in a text file to a string and then try to match a substring (search string) with a string (string)

But the error occurs when emitting metacharacters like / or #, etc.

0


source







All Articles