Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression for anything but an empty string

Tags:

c#

regex

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.

like image 717
cs0815 Avatar asked Jun 21 '10 14:06

cs0815


People also ask

What is regex for empty string?

As for the empty string, ^$ is mentioned by multiple people and will work fine. Ugly regex can in fact be handled by regex parsers. Not using a regex just because it's ugly is silly.

Can an empty set be in a regular expression?

∅, the empty set, is a regular expression. ∅ represent the language with no elements {}.

Is empty string regular?

(Not all languages are regular) The set of regular languages over alphabet ∑ is recursively defined as follows ● ∅, the empty set, is a regular language ● {ε}, the language consisting of only the empty string, is a regular language ● For any symbol a ∈ ∑, {a} is a regular language.


2 Answers

^(?!\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.

like image 143
Tim Pietzcker Avatar answered Oct 15 '22 06:10

Tim Pietzcker


In .Net 4.0, you can also call String.IsNullOrWhitespace.

like image 43
SLaks Avatar answered Oct 15 '22 05:10

SLaks