Malcolm
Malcolm

Reputation: 1807

How do I use a regular expression to match strings that don't start with an empty space?

I want a regular expression that checks that a string doesn't start with an empty space.

I want to do something like this:

Is the following ValidationExpression right for it?

string ValidationExpression = @"/^[^ ]/";

if (!String.IsNullOrEmpty(GroupName) && !Regex.IsMatch(GroupName, ValidationExpression))
{    
}

Upvotes: 1

Views: 328

Answers (4)

Asad
Asad

Reputation: 21928

You can also use:

   if(GroupName.StartsWith(string.Empty)); // where GroupName == any string

Upvotes: 6

Richie Cotton
Richie Cotton

Reputation: 121057

Regex rx = new Regex(@"^\s+");

You can check with

  Match m1 = rx.Match("   ");  //m1.Success should be true
  Match m2 = rx.Match("qwerty   ");  //m2.Success should be false

Upvotes: 3

Stephen Doyle
Stephen Doyle

Reputation: 3744

How about "^\S" This will make sure that the first character is not a whitespace character.

Upvotes: 7

Pascal MARTIN
Pascal MARTIN

Reputation: 400932

Something like this, maybe :

/^[^ ]/

And, for a couple of notes about that :

  • The first ^ means "string starts with"
  • The [^ ] means "one character that is not a space"
  • And the // are regex delimiter -- not sure if they are required in C#, though.

Upvotes: 0

Related Questions