Using Regex for spaces

Hello, I currently use !hasnext() to try and ensure that the input word doesn't have any characters other than letters, which works fine however I am not sure how to make it so that regex also detects whether or not any spaces are in the input
22 Replies
JavaBot
JavaBotthis hour
This post has been reserved for your question.
Hey @bed! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
dan1st
dan1stthis hour
You can use \s (any whitespace) or similar for spaces or just normal spaces to only match that
dan1st
dan1stthis hour
I assume you are using the Scanner#hasNext(Pattern) method?
Scanner (Java SE 21 & JDK 21)
declaration: module: java.base, package: java.util, class: Scanner
dan1st
dan1stthis hour
Note that by default, hasNext/next only checks one token so it doesn't go over multiple spaces you can use useDelimiter to change that behavior If you want to check it per line, you can set line breaks as delimiters
bed
bedOP23h ago
alr ty lemme check if it works rq yeah yeah thats fine
bed
bedOP23h ago
how come this doesn't work
No description
dan1st
dan1st23h ago
As I said, hasNext stops at \s by default
bed
bedOP23h ago
wdym im not following by this you mean that it only check to see if there is at least one space right? the input string has multiples spaces but "No!" still doesnt run
dan1st
dan1st23h ago
if you have an input like Hello World, hasNext/next only sees the Hello unless you have a custom delimiter
bed
bedOP23h ago
ohhh wait 1 second let me test smth eesh
dan1st
dan1st23h ago
hasNext/next only sees one token but you can configure what is used to split tokens
bed
bedOP23h ago
how would i make it only take that first word then? like if hello word was input how would i make it just take hello
dan1st
dan1st23h ago
hasNext()/next() literally does that by default without any regex
bed
bedOP23h ago
oh 1 sec again right i see what u mean well that solves my issue entirely ngl
JavaBot
JavaBot23h ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
dan1st
dan1st23h ago
nextLine --> read entire line next --> read one token (word)
bed
bedOP23h ago
alr thanks man
dan1st
dan1st23h ago
but you cannot just use nextLine after next
JavaBot
JavaBot23h ago
If Scanner#nextLine reads an empty line after calling a different Scanner#next method, take a look at this StackOverflow post.
bed
bedOP23h ago
alr tysm
dan1st
dan1st23h ago
np
JavaBot
JavaBot23h ago
Post Closed
This post has been closed by <@1167522887947796590>.

Did you find this page helpful?