There is already an other post for this but i can't comment on it. Sorry for that.
I used
var pattern = new RegExp('^[1-9]\d*$');
var result = fieldValue.search(pattern);
but i get a "-1" if I put 12
It allows me just number from 1 to 9 and no more.
Is there something wrong?
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
In this example, [0-9] matches any SINGLE character between 0 and 9 (i.e., a digit), where dash ( - ) denotes the range. The + , known as occurrence indicator (or repetition operator), indicates one or more occurrences ( 1+ ) of the previous sub-expression. In this case, [0-9]+ matches one or more digits.
E.g. (? i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode.
A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used.
Assuming the language is JavaScript, you need to escape the backslash character within a string for it to have a value of backslash:
'\d'
is a string with a value of d
'\\d'
is a string with a value of \d
var pattern = new RegExp('^[1-9]\\d*$');
JavaScript also has regular expression literals, which avoid the need for additional escape characters:
var pattern = /^[1-9]\d*$/;
If you wanted to extend this to allow for positive integers with leading zeros, you could do this:
var pattern = /^\d*[1-9]+\d*$/
This will allow 001 as a valid input (which it is), while not allowing 000 (which is not non zero).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With