Scanner.next() from a BufferedReader
I am trying to scan text from a reader based on a delimiter "()()"
by using the Scanner.next()
method. Here is my code:
public static void main(String[] args)
{
String buffer = "i want this text()()without this text()()";
InputStream in = new ByteArrayInputStream(buffer.getBytes());
InputStreamReader isr = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(isr);
Scanner scan = new Scanner(reader);
scan.useDelimiter("/(/)/(/)");
String found = scan.next();
System.out.println(found);
}
The problem is, the entire buffer is returned:
i want this text()()without this text()()
I only want the first next() iteration to return:
i want this text
and the next next() iteration to return:
without this text
Any suggestions how I can scan t开发者_开发技巧he reader by only delimiting strings ending in ()()
?
Your useDelimiter
argument is incorrect - you're using forward slashes instead of backslashes when you try to escape the parentheses. You need to escape the backslashes in Java terms, too:
scan.useDelimiter("\\(\\)\\(\\)");
EDIT: Rather than escaping this yourself, you can use Pattern.quote
:
String rawDelimiter = "()()";
String escaped = Pattern.quote(rawDelimiter);
scan.useDelimiter(escaped);
精彩评论