Reputation: 513
How to write regular expression that matches only numbers,text and only these two special characters # and - [a-zA-Z0-9#-\s]+ anything else should be rejected
Upvotes: 0
Views: 2029
Reputation: 4110
I believe the following pattern would work in C#:
string pattern = @"^[a-zA-Z\d\s#-]*$";
I just tried a couple of test cases in C# interactive:
Regex.Match("", pattern).Success
> true
Regex.Match("asdf 2F#-#-", pattern).Success
> true
Regex.Match("asdf~asdf", pattern).Success
> false
If you don't want to accept an empty string, simply change the * to + in the pattern. Also, you didn't state that you wanted to match whitespace in your question but your example pattern does match whitespace. If you don't want to match whitespace, remove the \s.
Update: Edited per Rawling's suggestions.
Upvotes: 3
Reputation: 76
You could a regular expression similar to this
^(\d|[a-z]|[A-Z]|#|-)*$
Below the code I used for checking the regular expression in c#:
string input = @"343243-2df---ds#SFD#FD";
string pattern = @"^(\d|[a-z]|[A-Z]|#|-)*$";
Console.WriteLine(Regex.Match(input, pattern).Success);
Console.ReadLine();
Also, for future reference material, you could see this regular expression site: http://www.regular-expressions.info/
Upvotes: 3