Java:扫描字符串中的模式
这大概是一个快手吧。为什么这段代码不返回任何内容?
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
try {
Scanner sc = new Scanner("asda ASA adad");
String pattern = "[A-Z]+";
while ((sc.hasNext(pattern))) {
System.out.println(sc.next(pattern));
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is probably a quicky. Why does this code not return anything?
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
try {
Scanner sc = new Scanner("asda ASA adad");
String pattern = "[A-Z]+";
while ((sc.hasNext(pattern))) {
System.out.println(sc.next(pattern));
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
hasNext(String pattern)
仅当下一个标记与该模式匹配时才返回true
。在您的情况下,“asda”
是下一个标记,它与“[AZ]+”
不匹配。该文档很清楚,“扫描仪不会前进超过任何输入”。如果您将模式更改为
"[A-Za-z]+"
,那么您将获得三个标记,这可能正是您想要的。如果实际上您只想获取与
"[AZ]+"
匹配的标记,那么您可以执行以下任一操作:useDelimiter("[^AZ] +")
,然后只需调用next()
skip("[^AZ]+")
findInLine("[AZ]+ ")
提示:如果性能至关重要,您需要使用这些方法的预编译
Pattern
重载。提示:请记住,
"Xooo ABC"
有两个"[AZ]+"
匹配项。如果这不是您想要的,那么正则表达式必须更复杂一些。或者您始终可以简单地丢弃不匹配的标记。hasNext(String pattern)
only returnstrue
if the next token matches the pattern. In your case,"asda"
is the next token, and that does NOT match"[A-Z]+"
. The documentation is clear in that "[the] scanner does not advance past any input".If you change the pattern to
"[A-Za-z]+"
, then you'd get three tokens, which may be what you intended.If in fact you only want to get tokens that match
"[A-Z]+"
, then you can do any of the following:useDelimiter("[^A-Z]+")
, then simply invokenext()
skip("[^A-Z]+")
findInLine("[A-Z]+")
Tip: if performance is critical, you'd want to use the precompiled
Pattern
overloads of these methods.Tip: do keep in mind that
"Xooo ABC"
has two"[A-Z]+"
matches. If this is not what you want, then the regex will have to be a bit more complicated. Or you can always simply discard non-matching tokens.更改
为
Change
to
如果您希望打印出分隔符包围的所有单词,您可能需要安全起见并完全排除该模式。这样,您就不会遇到包含不在您的模式中的字符的单词,这会导致您的程序退出该循环(就像它当前正在做的那样)。例如:
If you are looking to print out all words surrounded by your delimiter you might want to be safe and exclude the pattern altogether. That way you don't come across a word that contains a character not in your pattern which would cause your program exit that loop (as it's currently doing). For example: