I want the scanner to ignore three things: empty spaces, "/"
and "!"
.
What is the correct argument to use in the useDelimiter
method?
Asked
Active
Viewed 510 times
2
![](../../users/profiles/2422776.webp)
Mureinik
- 252,575
- 45
- 248
- 283
2 Answers
1
Scanner's delimiter is just a pattern, so you could use the following:
sc.useDelimiter("[\\s/!]*");
![](../../users/profiles/2422776.webp)
Mureinik
- 252,575
- 45
- 248
- 283
-
1Why are you using `#`? – OneCricketeer Aug 14 '17 at 13:59
-
1i want to give the scanner something like "Anna Mills/Female/18" and then use System.out.println(scan.next()) to get each word on separate lines. so the scanner should ignore both empty space and " / " sign. i used your suggested code and it doesn't do that... – Aug 14 '17 at 14:02
-
For some reason I had in my mind that OP was using `#` as a possible delimiter. Meant to use `/` - edited and fixed. – Mureinik Aug 14 '17 at 14:40
1
useDelimiter
takes a regex argument docs:
pattern
- A string specifying a delimiting pattern
So just make sure the string is in regex form.
Whitespace in regex is \s
, escape that to become \\s
. /
is still /
and !
is still !
. You then use |
to act as an "or" operator to say "either one of these".
Here's how to do it:
scanner.useDelimiter("\\s|/|!");
If you want to say that "consecutive whitespaces slashes and exclamation marks also count as delimiter", then you can add a quantifier +
to the whole thing:
scanner.useDelimiter("(\\s|/|!)+");
![](../../users/profiles/5133585.webp)
Sweeper
- 145,870
- 17
- 129
- 225