Java Scanner with regex delimiter

后端 未结 2 2111
心在旅途
心在旅途 2021-02-11 02:59

Why does the following code return false?

Scanner sc = new Scanner(\"-v \");
sc.useDelimiter(\"-[a-zA-Z]\\\\s+\");
System.out.println(sc.hasNext());
2条回答
  •  隐瞒了意图╮
    2021-02-11 03:39

    A scanner is used to break up a string into tokens. Delimiters are the separators between tokens. The delimiters are what aren't matched by the scanner; they're discarded. You're telling the scanner that -[a-zA-Z]\\s+ is a delimiter and since -v matches that regex it skips it.

    If you're looking for a string that matches the regex, use String.matches().

    If your goal really is to split a string into tokens then you might also consider String.split(), which is sometimes more convenient to use.

提交回复
热议问题