为什么第一个 block 有效而第二个 block 不有效?
int numberOfDigits = 2;
Pattern p = Pattern.compile("[01]{"+numberOfDigits+"}");
Matcher m = p.matcher("101100101011010011111000");
while(m.find()){
System.out.println(m.group());
}
block 2
Scanner scannerSegment = new Scanner("101100101011010011111000");
while(scannerSegment.hasNext(p)){
String segment = scannerSegment.next(p);
System.out.println(segment);
}
最佳答案
Scanner
不是使用其 hasNext(Pattern pattern)
方法检索模式的合适实用程序。它将检查 next complete token 是否具有请求的模式。
Java API是最好的文档。
部分摘录:
hasNext() : Returns true if the next complete token matches the specified
pattern. A complete token is prefixed and postfixed by input that matches
the delimiter pattern.`
因此,如果您将输入更改为由空格或任何其他分隔符分隔(必须在定义 Scanner
对象后设置其他分隔符),它将起作用。所以这应该有效(对于当前模式):
Scanner scannerSegment = new Scanner("10 11 00 10 10 11 01 00 11 11 10 00");
即使这样也行得通(对于当前模式):
Scanner scannerSegment = new Scanner("10,11,00,10,10,11,01,00,11,11,10,00");
scannerSegment.useDelimiter(",");
编辑:Scanner使用分隔符模式将其输入分解为标记,默认情况下匹配空格。
关于Java Scanner vs Matcher——正则表达式,Matcher 有效,Scanner 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16065144/