# Regular Expressions - Character Class Question

## Recommended Posts

I want to check if a form field's value is between 1-10. I can do [1-9] but then its missing 10.and if i do [1-9][0], then someone can enter in 20, 30, 40 etc.Any way of doing this without doing an if statement?

##### Share on other sites

In regular expressions, [0-9] doesn't mean a number from 0 to 9, it means any character between 0 and 9.Regular expressions don't recognize numeric values, only strings.If you want to check for 1 to 9 or 10, then use a vertical bar:

`([1-9]|10)`

And if you don't want to create a back reference:

`(?:[1-9]|10)`

But for something so simple as this, I don't even recommend a regular expression. Just check the value, because regular expressions take more processing.

`if(\$_POST['field'] < 1 || \$_POST['field'] > 10) {  echo "The field must have a value between 1 and 10";}`

##### Share on other sites

In regular expressions, [0-9] doesn't mean a number from 0 to 9, it means any character between 0 and 9.Regular expressions don't recognize numeric values, only strings.
so what is the order of characters then? a-z then 0-9? what about capital A?
##### Share on other sites

so what is the order of characters then? a-z then 0-9? what about capital A?
In a regular expression, a series of characters between square brackets indicate that one single character of the list can be selected:This regular expression matches both "grey" and "gray," but not "graey":
`/gr[ae]y/`

##### Share on other sites

what about this: [a-zA-Z0-9] ... Could this be rewritten like [a-9]?

##### Share on other sites

what about this: [a-zA-Z0-9] ... Could this be rewritten like [a-9]?
No, because 9 goes before a in the ASCII system.You can check this table to see which characters can have hyphens between them:http://asciitable.com/If you write [Z-a] it will allow the following characters: Z[\]^_`a Edited by Ingolme

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account