[c#] ^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

The regular expression ^[A-Za-Z ][A-Za-z0-9 ]* describe "first letter should be alphabet and remaining letter may be alpha numerical". But how do I also allow special characters? When I enter "C#" it is raising an error.

How do I enter a special character and first letter should alphabet?

This question is related to c# regex

The answer is


Try this:

^[A-Za-z ].*


This expression will check if the first letter to be alphabetic and the remaining characters to be alphanumeric or any of the following special characters: @,#,%,&,

^[A-Za-z][A-Za-z0-9@#%&\*]*$

This expression will force the first letter to be alphabetic and the remaining characters to be alphanumeric or any of the following special characters: @,#,%,&,*

^[A-Za-z][A-Za-z0-9@#%&*]*$

First must be Alphabet and then dot not allowed in target string. below is code.

        string input = "A_aaA";

        // B
        // The regular expression we use to match
        Regex r1 = new Regex("^[A-Za-z][^.]*$"); //[\t\0x0020] tab and spaces.

        // C
        // Match the input and write results
        Match match = r1.Match(input);
        if (match.Success)
        {
            Console.WriteLine("Valid: {0}", match.Value);

        }
        else
        {
            Console.WriteLine("Not Match");
        }


        Console.ReadLine();

A lot of the answers given so far are pretty good, but you must clearly define what it is exactly that you want.

If you would like a alphabetical character followed by any number of non-white-space characters (note that it would also include numbers!) then you should use this:

^[A-Za-z]\S*$

If you would like to include only alpha-numeric characters and certain symbols, then use this:

^[A-Za-z][A-Za-z0-9!@#$%^&*]*$

Your original question looks like you are trying to include the space character as well, so you probably want something like this:

^[A-Za-z ][A-Za-z0-9!@#$%^&* ]*$

And that is my final answer!

I suggest taking some time to learn more about regular expressions. They are the greatest thing since sliced bread!

Try this syntax reference page (that site in general is very good).


this expression is to get only numbers

    If Regex.IsMatch(mystring, "^[A-Za-z ].*|\s") Then
        MessageBox.Show("please fill the box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
       
    ElseIf (mystring = "") Then
        MessageBox.Show("please fill the box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
      
    End If

How about

^[A-Za-z]\S*

a letter followed by 0 or more non-space characters (will include all special symbols).


^[A-Za-z](\W|\w)*

(\W|\w) will ensure that every subsequent letter is word(\w) or non word(\W)

instead of (\W|\w)* you can also use .* where . means absolutely anything just like (\w|\W)