开发者

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜