Loading ...

C#: Check blank space with REGEX | CodeAsp.Net

C#: Check blank space with REGEX

 /5
0 (0votes)

In this blog I will show how to check whether a text contains blank space or not. I have used REGEX with C# for checking the blank space existence. This is a very common need when we are taking some input from user and we want to check whether that string contains blank space or not. Below is the sample code for it:

#region Using Directives

using System;
using System.Text.RegularExpressions;

#endregion

public class Example
{
    static void Main()
    {
        string input = "hello";
        string regex = @"^[\S]*$";
        bool isMatch = false;
        isMatch = Regex.IsMatch(input, regex);
        Console.WriteLine(isMatch ? "{0}: Matched" : "{0}: Not Matched", input);

        input = "hello good";
        isMatch = Regex.IsMatch(input, regex);
        Console.WriteLine(isMatch ? "{0}: Matched" : "{0}: Not Matched", input);

        Console.ReadLine();
        //Output:

        //hello: Matched
        //hello good: Not Matched
    }
}


Explanation of REGEX used above:

^[\S]*$

Assert position at the beginning of the string «^»

Match a single character that is a “non-whitespace character” «[\S]*»

   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»

Assert position at the end of the string (or before the line break at the end of the string, if any) «$»


Created with RegexBuddy


Hope this helps!

Comments (no comments yet)

Top Posts