87

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.

3
  • I am sorry I edited my question as it had to be 'negated' Commented Jun 21, 2010 at 14:56
  • 4
    If I may, what's the compelling reason to use a regular expression rather than the built-in function? Commented Jun 21, 2010 at 17:04
  • 1
    In .net vernacular, only your first example ("") is considered an "empty string". The others are purely whitespace--but not empty. This seemingly minor difference has yielded some overly complicated answers below. Commented Apr 30, 2015 at 18:06

10 Answers 10

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

Sign up to request clarification or add additional context in comments.

10 Comments

only whitespace or an empty string, +1
As well as the empty string. (A small distinction, but sometimes an important one, though not in this case as csetzkorn wants that.)
I think I know why it does not work. How do I negate your suggestion? Meaning - match everything but not empty strings. Thanks and sorry about the confusion!
The negation would be \S which would match any non-whitespace character
(?!\s*$) is a negative lookahead, not positive
|
32

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

4 Comments

Certainly the easiest solution ^^
If you're not on .Net 4.0, you can use String.IsNullOrEmpty(variable.Trim()) to achieve essentially the same thing.
I have to use regular expressions in my chosen validation framework. thanks anyway.
@IanP - no you can't. It'll fail if variable is null.
10

Assertions are not necessary for this. \S should work by itself as it matches any non-whitespace.

1 Comment

This is the right answer! Many of the others are overly complicated, because a.) they myopically focus on the OP's term "empty string" when the examples given clearly include strings consisting of various amounts of whitespace, or b.) they missed the clearly-stated requirement that the OP wants a regex solution.
8

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

Comments

4

You can do one of two things:

  • match against ^\s*$; a match means the string is "empty"
    • ^, $ are the beginning and end of string anchors respectively
    • \s is a whitespace character
    • * is zero-or-more repetition of
  • find a \S; an occurrence means the string is NOT "empty"
    • \S is the negated version of \s (note the case difference)
    • \S therefore matches any non-whitespace character

References

Related questions

Comments

1

You could also use:

public static bool IsWhiteSpace(string s) 
{
    return s.Trim().Length == 0;
}

4 Comments

I have to use regular expressions in my chosen validation framework. thanks anyway.
It will return true with any text (which doesn't contain trailing or leading whitspace). IsWhiteSpace("test") => true.
@csetz I understand that. However, other people may find value in knowing there are other ways to solve this problem. Some people don't like regex at all.
@Shimrod, yeah, my bad. I was thinking one thing, but wrote another. It has been fixed.
1

We can also use space in a char class, in an expression similar to one of these:

(?!^[ ]*$)^\S+$
(?!^[ ]*$)^\S{1,}$
(?!^[ ]{0,}$)^\S{1,}$
(?!^[ ]{0,1}$)^\S{1,}$

depending on the language/flavor that we might use.

RegEx Demo

Test

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(?!^[ ]*$)^\S+$";
        string input = @"

            abcd
            ABCD1234
            #$%^&*()_+={}
            abc def
            ABC 123
            ";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

C# Demo


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Comments

0

I think [ ]{4} might work in the example where you need to detect 4 spaces. Same with the rest: [ ]{1}, [ ]{2} and [ ]{3}. If you want to detect an empty string in general, ^[ ]*$ will do.

1 Comment

But you will not match a "tab" character, which is still whitespace. A \s instead of the [ ] fixes that.
0

If you want to find out if a string is not just white-space characters, just ask the regular expression to find literally any non-white-space character:

/[^\s]/

Comments

-2

Create "regular expression to detect empty string", and then inverse it. Invesion of regular language is the regular language. I think regular expression library in what you leverage - should support it, but if not you always can write your own library.

grep --invert-match

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.