I am trying to create a regex that will return false if the String pattern contains whitespace or is empty. So far I have this
[^\s]
I think that will make sure the string does not contain whitespace but I am unsure of how to also check to make sure it is not empty. Any help would be appreciated.
/^$|\s+/
if this matched, there's whitespace or its empty.
In my understanding you want to match a non-blank and non-empty string, so the top answer is doing the opposite. I suggest:
(.|\s)*\S(.|\s)*
- this matches any string containing at least one non-whitespace character (the \S
in the middle). It can be preceded and followed by anything, any char or whitespace sequence (including new lines) - (.|\s)*
.
You can try it with explanation on https://regex101.com/.
Most regular expression engines support "counter part" escape sequences. That is, for \s
(white-space) there's its counter part \S
(non-white-space).
Using this, you can check, if there is at least one non-white-space character with ^\S+$
.
PCRE for PHP has several of these escape sequences.
I ended up using something similar to the accepted answer, with minor modifications
(^$)|(\s+$)
Explanation by the Expresso
Select from 2 alternatives (^$)
[1] A numbered captured group ^$
Beginning of line ^
End of line $
[2] A numbered captured group (\s+$)
Whitespace, one or more repetitions \s+
End of line $
A little late, but here's a regex I found that returns 0 matches for empty or white spaces:
/^(?!\s*$).+/
You can test this out at regex101
/^$|\s+/
This matches when empty or white spaces
/(?!^$)([^\s])/
This matches when its not empty or white spaces
/^[\s]*$/
matches empty strings and strings containing whitespaces only