views:

107

answers:

4
+1  Q: 

Regular Expression

I want regular expression that checks that the string doesnt start with an empty space.

Some what like this i want to do :

Is the below ValidationExpression right for it :

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

if (!String.IsNullOrEmpty(GroupName) && !Regex.IsMatch(GroupName, ValidationExpression))
{    
}
+1  A: 

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.
Pascal MARTIN
Hey hi Pascal i have updated my question : so is the value i am giving to string ValidationExpression = @"/^[^ ]/"; is right
Malcolm
+4  A: 

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

Stephen Doyle
+5  A: 

just a suggestion, you can also use

   if(GroupName.StartsWith(string.Empty)); // where GroupName == any string
Asad Butt
Yes - Regular expression is hammer for this problem. or value[0] == ' '
Fakrudeen
sure, must not - DRY
Asad Butt
And unless failing validation is important, one could just .Trim or .TrimStart and preemptively correct the issue.
Mark Maslar
+3  A: 
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
Richie Cotton
\s means white-space, use \S that means none white-space
zwi
@zwi: In the context of the program, I'm not sure it matters much which one you use, but well spotted nonetheless.
Richie Cotton