C# regex that should start with alpha numeric but not with space

sravan kumar 121 Reputation points
2021-01-25T12:30:58.67+00:00

Hi ,

I am trying for regex that should take only AlphaNumeric as first character but when i go with [A-za-z0-9], it is also taking white space as valid, how to avoid space as first character in regex C#.

please help.

below are some valid and invalid conditions (ignore starting and ending " ).

Invalid scenarios:

"!test"
"@test "
" Test"

Valid scenarios:

Test@3
test!12a
7test#1
67899
Test

Thanks in advance :)

Regards,
Sravan kumar

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,346 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,246 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,205 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yihui Sun-MSFT 801 Reputation points
    2021-01-26T10:56:25.607+00:00

    Hi @sravankumar-3852,

    Regular expressions can be written like this:

    var pattern = "^[a-zA-Z0-9]\\S+$";  
    

    Below is the demo I tested, you can refer to it.

        class Program  
        {  
            static void Main(string[] args)  
            {  
                var pattern = "^[a-zA-Z0-9]\\S+$";  
                Console.WriteLine("Invalid scenarios:");  
                Console.WriteLine("!test:{0}", Regex.Match("!test", pattern).Success);  
                Console.WriteLine("@Test:{0}", Regex.Match("@Test", pattern).Success);  
                Console.WriteLine(" Test:{0}", Regex.Match(" Test", pattern).Success);  
                Console.WriteLine("\n\nValid scenarios:");  
                Console.WriteLine("Test@3:{0}", Regex.Match("Test@3", pattern).Success);  
                Console.WriteLine("test!12a:{0}", Regex.Match("test!12a", pattern).Success);  
                Console.WriteLine("7test#1:{0}", Regex.Match("7test#1", pattern).Success);  
                Console.WriteLine("67899:{0}", Regex.Match("67899", pattern).Success);  
                Console.WriteLine("Test:{0}", Regex.Match("Test", pattern).Success);  
                Console.ReadLine();  
            }  
        }  
    

    Here is the result.
    60593-result.png


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best Regards,
    YihuiSun

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Viorel 111.8K Reputation points
    2021-01-25T12:40:54.21+00:00

    Try several expressions:

    ^[a-zA-Z0-9]

    (?i)^[a-z0-9]

    ^(\p{L}|\p{N})

    0 comments No comments