How to combine nothing but "just spaces" using .Net Regex

I want to match a string when it contains anything but not "just spaces".

The spaces are in order and can be anywhere while there is something else.

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

(EDIT: I want to do this in a 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(); } } 

What gives this conclusion:

 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='' 

I want it:

 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

+4
source share
3 answers

There is no need for regular expression. You can use string.IsNullOrWhitespace()

The regular expression is as follows:

 [^ ] 

What this does is simple: it checks to see if your string contains anything that is not space.

I adjusted your code a bit 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 template.

+6
source

I would use

 ^\s*\S+.*?$ 

Regular expression violation ...

  • ^ - start of line
  • \s* - zero or more whitespace characters
  • \S+ - one or more characters without spaces
  • .*? - any characters (whitespace or not - not greedy β†’ match as little as possible)
  • $ is the end of the line.
+6
source

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

0
source

All Articles