4

I want to match a string when it contains anything but not 'only spaces'.

Spaces are fine, and can be anywhere as long as there is something else.

I can't seem to get a match when a space appears anywhere.

(EDIT: I am looking to do this in regex as I ultimately want to combine it with other regex patterns using | )

Here is my test code:

class Program
{
    static void Main(string[] args)
    {
        List<string> strings = new List<string>() { "123", "1 3", "12 ", "1  " , "  3", "   "};

        string r = "^[^ ]{3}$";
        foreach (string s in strings)
        {
            Match match = new Regex(r).Match(s);
            Console.WriteLine(string.Format("string='{0}', regex='{1}', match='{2}'", s, r, match.Value));
        }
        Console.Read();
    }
}

Which gives this output:

string='123', regex='^[^ ]{3}$', match='123'
string='1 3', regex='^[^ ]{3}$', match=''
string='12 ', regex='^[^ ]{3}$', match=''
string='1  ', regex='^[^ ]{3}$', match=''
string='  3', regex='^[^ ]{3}$', match=''
string='   ', regex='^[^ ]{3}$', match=''

What I want is this:

string='123', regex='^[^ ]{3}$', match='123' << VALID
string='1 3', regex='^[^ ]{3}$', match='1 3' << VALID
string='12 ', regex='^[^ ]{3}$', match='12 ' << VALID
string='1  ', regex='^[^ ]{3}$', match='1  ' << VALID
string='  3', regex='^[^ ]{3}$', match='  3' << VALID
string='   ', regex='^[^ ]{3}$', match=''    << NOT VALID

Thanks

3 Answers 3

7

I'd use

^\s*\S+.*?$

Breaking down the regex...

  • ^ - start of line
  • \s* - zero or more whitespace characters
  • \S+ - one or more non-whitespace characters
  • .*? - any characters (whitespace or not - non-greedy -> match as few as possible)
  • $ - end of line.
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting, thanks @Grhm! It doesn't seem to allow the new-line character \n, should \n* be placed immediately after ^?
@Ian Campbell you probably need to add a SingleLine option to make the . character march newlines. See msdn.microsoft.com/en-us/library/…
6

No need for a regular expression here. You can use string.IsNullOrWhitespace()

A regular expression is this:

[^ ]

What this does is simple: It checks if your string contains anything that is not a space.

I adjusted your code slightly by adding match.Success to the output:

var strings = new List<string> { "123", "1 3", "12 ", "1  " , "  3", "   ", "" };

string r = "[^ ]";
foreach (string s in strings)
{
    Match match = new Regex(r).Match(s);
    Console.WriteLine(string.Format("string='{0}', regex='{1}', match='{2}', " +
                                    "is match={3}", s, r, match.Value,
                                    match.Success));
}

The result will be:

string='123', regex='[^ ]', match='1', is match=True
string='1 3', regex='[^ ]', match='1', is match=True
string='12 ', regex='[^ ]', match='1', is match=True
string='1  ', regex='[^ ]', match='1', is match=True
string='  3', regex='[^ ]', match='3', is match=True
string='   ', regex='[^ ]', match='', is match=False
string='', regex='[^ ]', match='', is match=False

BTW: Instead of new Regex(r).Match(s) you should use Regex.Match(s, r). This allows the regex engine to cache the pattern.

8 Comments

Hi Daniel. I would like to use regex here if possible as I'm using regex for some other validation, not just the spaces issue.
@errolc: Do you really need the value of the string as part of match.Value? Or is all you are interested in that match.Success is true?
I just want to know if it matches. I don't care what the value is. I'm using it validate a string. Either its valid according to the regex 'validator'....in which case yay, continue or..... it isnt, barf and exit.
In that case, the simple expression from my answer is all you need. It will only match if there is a character other than a space anywhere in your string
So for this case. A string with something in it would be valid but a blank string would not be.
|
0

What about using ^\s+$ and simply negating the result of Match()?

2 Comments

IsMatch() can also be used.
Thanks to both of you. Time for me to look more closely at the Regex class.

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.