views:

58

answers:

2

I've got this java function that extracts strings from Inputstreams and returns a List. It uses java.util.Scanner and java.util.regex.Pattern.

Problem is, it only seems to work the first time I call it. If I reverse my calls, again only the first one works, the second call never returns any matches.

List lsphones = extract(is,pattern,0); List lsemails = extract(is,pattern",0);

I suspect I need to reset the Lists or something in the funciton -if not the function itself somehow. I've tried but keep getting exceptions when I do.

public static List<String> extract(InputStream in,String matchpattern,int grp) {  

.. scanner.close(); return what

I'm developing this in the Android SDK.

+2  A: 

Does your extract method read until the end of the stream? I suspect you need to close and reopen the stream to start again from the beginning. If this is the case, a better approach would be to do all your matching on one pass through the stream.

Skip Head
It complicated the regular expression, but I just consolidated into one pass. It's a lot faster now. thanks.
cyberpine
A: 

If the input stream supports mark (markSupported() == true) then you could possibly use mark() ... reset() in your method. If not, you are going to have to either recreate the input stream or change your method so you can pass in the result (e.g. byte[] or String) of reading the input stream prior to using it.

Michael Rutherfurd
Please use `if (in.markSupported()) ...` instead of `if (in.markSupported() == true) ...`.
Willi
Good point. I was try to write English rather than providing a code sample, when I should have just provided the code sample up front. I can't think of a good reason for an actual if statement to explicitly check equals true (or false for that matter).
Michael Rutherfurd