我正在尝试使用 Scanner.next()
方法根据定界符 "()()"
扫描来自阅读器的文本。这是我的代码:
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);
}
问题是,整个缓冲区被返回:
i want this text()()without this text()()
我只想返回第一个 next() 迭代:
i want this text
和下一个 next() 迭代返回:
without this text
关于如何通过仅分隔以 ()()
结尾的字符串来扫描阅读器有什么建议吗?
最佳答案
您的 useDelimiter
参数不正确 - 当您尝试转义括号时,您使用的是正斜杠而不是反斜杠。您还需要转义 Java 术语中的反斜杠:
scan.useDelimiter("\\(\\)\\(\\)");
编辑:与其自己转义,不如使用 Pattern.quote
:
String rawDelimiter = "()()";
String escaped = Pattern.quote(rawDelimiter);
scan.useDelimiter(escaped);
关于java - 来自 BufferedReader 的 Scanner.next(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6327119/