Johnston
Johnston

Reputation: 2873

Regex Expression Only Numbers and Characters

I created the following regex expression for my C# file. Bascily I want the user's input to only be regular characters (A-Z lower or upper) and numbers. (spaces or symbols ).

[a-zA-Z0-9]

For some reason it only fails when its a symbol on its own. if theres characters mixed with it then the expression passes.

I can show you my code of how I implment it but I think its my expression.

Thanks!

Upvotes: 2

Views: 18875

Answers (4)

Ry-
Ry-

Reputation: 224886

The problem is that it can match anywhere. You need anchors:

^[a-zA-Z0-9]+\z

^ matches the start of a string, and \z matches the end of a string.

(Note: in .NET regex, $ matches the end of a string with an optional newline.)

Upvotes: 8

Oliver
Oliver

Reputation: 1530

This is because it will match any character in the string you need the following. Forces it to match the entire string not just part of it

^[0-9a-zA-Z]*$

Upvotes: 4

Francis Gagnon
Francis Gagnon

Reputation: 3675

That regex will match every single alphanumeric character in the string as separate matches.

If you want to make sure the whole string the user entered only has alphanumeric characters you need to do something like:

^[a-zA-Z0-9]+$

Upvotes: 3

user849425
user849425

Reputation:

Are you making sure to check the whole string? That is are you using an expression like ^[a-zA-Z0-9]*$ where ^ means the start of the string and $ means the end of the string?

Upvotes: 1

Related Questions