I don't know how MVC matters, but if your identifier is an integer, this BRE should do:
^[1-9][0-9]*$
If you want to match real numbers (float), not integers, you need to handle the above case, as well as regular decimal numbers (i.e. 2.5 or 3.3Μ
), cases when your pattern is between 0 and 1 (i.e. e. 0.25 ), as well as the case when your template has a decimal part equal to 0. (i.e. 2.0 ). And while we are on it, we will add support for leading zeros to integers (i.e. 005 ):
^(0*[1-9][0-9]*(\.[0-9]+)?|0+\.[0-9]*[1-9][0-9]*)$
Please note that this second is an extended RE. The same can be expressed in Basic RE, but almost everyone understands ERE these days. Let me break down the expression into parts that are easier to assimilate.
^(
The carriage matches the zero value at the beginning of the line, so before your regular expression with a carriage, it binds it to the beginning of the line. The opening bracket is due to the or-bar below. More on this later.
0*[1-9][0-9]*(\.[0-9]+)?
This matches any integer or any floating point number higher than 1. Thus, our 2.0 will match, but 0.25 won't. 0* at the beginning processes leading zeros, therefore 005 == 5 .
|
In this context, the pipe symbol is "or-bar". To evaluate this expression, it takes precedence over everything else and effectively combines the two regular expressions together. Parentheses are used to group multiple expressions separated by or-bars.
And the second part:
0+\.[0-9]*[1-9][0-9]*
This matches any number starting with one or more characters 0 (replace + by * with zero or more zeros, i.e. .25 ), followed by a period, followed by a string of digits that includes at least one that does not is 0 . Thus, this corresponds to all above 0 and below 1 .
)$
And finally, we close the parentheses and attach the regular expression to the end of the line with a dollar sign, just like a carriage is attached to the beginning of the line.
Of course, if you let your programming language evaluate something numerically, rather than try to match it with a regular expression, you will save headaches and a processor.