Reputation: 37
My requirement is
"A string should not be blank or empty"
Eg., A String can contain any number of characters or strings followed by any special characters but should never be empty for eg., a string can contain "a,b,c" or "xyz123abc" or "12!@$#%&*()9" or " aa bb cc "
So, this is what i tried Regex for blank or space:-
^\s*$
^ is the beginning of string anchor
$ is the end of string anchor
\s is the whitespace character class
* is zero-or-more repetition of
I'm stuck on how to negate the regex ^\s*$ so that it accepts any string like "a,b,c" or "xyz" or "12!@$#%&*()9"
Any help is appreciated.
Upvotes: 2
Views: 1479
Reputation: 1863
to me two simple ways to express it are (both no need for anchoring):
s.trim() =~ /.+/
or
s =~ /\S+/
the first assumes you know how trim() works, the second assumes the meaning of \S. Of course
!s.allWhitespace
is perfect, again if you know it exists
Upvotes: 1
Reputation: 17131
\S
\S
matches any non-white space character
Each character class has it's own anti-class defined, so for \w
you have \W
for \s
you have \S
for \d
you have \D
etc.
http://www.regular-expressions.info/charclass.html
Your regex engine may not support \S
. If this is the case you use [^ \t\v]
if you support unicode (which you should) there are more space types that you should watch for.
If both your regex engine and you support unicode AND \S
is not supported by your regex engine then you'll probably want to use (if you care about people entering different unicode space types):
[^ \r\f\t\v\u0085\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u200B\u2028\u2029\u202F\u205F\u3000\uFEFF]
http://www.cs.tut.fi/~jkorpela/chars/spaces.html
http://en.wikipedia.org/wiki/Whitespace_character#Unicode
Upvotes: 1
Reputation: 19219
No need for a regex. In Groovy you have the isAllWhitespace
method:
groovy:000> "".allWhitespace
===> true
groovy:000> " \t\n ".allWhitespace
===> true
groovy:000> "something".allWhitespace
===> false
So asking !yourString.allWhitespace
should tell you if your string is something else than empty or blank :)
Upvotes: 3
Reputation: 171084
is this in a grails domain class?
if so, just use the blank constraint
Upvotes: 0
Reputation: 72981
The following regular expression will ensure that a string contains at least 1 non-whitespace character.
^(?!\s*$).+
Note: I am not familiar with groovy. But I would imagine there is a native functions (trim
, empty
, etc) that test this more naturally than a regular expression.
Upvotes: 0