Reputation: 548
What I am trying to do is make sure that there is a space after something, as well as before the next thing, but there can also be words in-between
eg hello <word> goodbye
or hello goodbye
when I try to check for this in regex hello\s+.*\s+goodbye
The problem with this code is that if there is not a word in the middle of hello and goodbye, then it will look for two spaces, and then count it as not seeing the correct thing.
Basically, I am trying to make sure that there is a space, and only one space, if there is or is not a word between hello and goodbye.
EDIT: still getting used to this strict definition of regex. the problem is also that there is the possibility of having something like helloabcdef <word> goodbye
or hello <word> aksdjhsdflkhgoodbye
which should show as false
Upvotes: 0
Views: 74
Reputation: 213351
If you want to match only one space, then why are you using \s+
with quantifier? That will match 1 or more spaces. You should use just \s
.
Now as for your issue, you can use this regex for matching those strings:
hello\s(\S+\s)?goodbye
Note the use of \S+
. That makes sure that the capture group will match only when there is at least one non-whitespace character between the 2 spaces. Using .
won't work, as it matches any character, and hence will match a space also. And, if you use \S*
instead, then it will also match the following string: hello\s\sgoodbye
. Note there are 2 spaces there.
Upvotes: 3