regular expression for anything but an empty string
Is it possible to use a regular expression to detect anything that is NOT an "empty string" like this:
string s1 = "";
string s2 = " ";
string s3 = " ";
string s4 = " ";
etc.
I know I could use trim etc. but I would like to use a regular expression.
^(?!\s*$).+
will match any string that contains at least one non-space character.
So
if (Regex.IsMatch(subjectString, @"^(?!\s*$).+")) {
// Successful match
} else {
// Match attempt failed
}
should do this for you.
^
anchors the search at the start of the string.
(?!\s*$)
, a so-called negative lookahead, asserts that it's impossible to match only whitespace characters until the end of the string.
.+
will then actually do the match. It will match anything (except newline) up to the end of the string. If you want to allow newlines, you'll have to set the RegexOptions.Singleline
option.
Left over from the previous version of your question:
^\s*$
matches strings that contain only whitespace (or are empty).
The exact opposite:
^\S+$
matches only strings that consist of only non-whitespace characters, one character minimum.
In .Net 4.0, you can also call String.IsNullOrWhitespace
.
Assertions are not necessary for this. \S
should work by itself as it matches any non-whitespace.
What about?
/.*\S.*/
This means
/
= delimiter.*
= zero or more of anything but newline\S
= anything except a whitespace (newline, tab, space)
so you get
match anything but newline + something not whitespace + anything but newline