I am trying to make a regex to allow the following
1
1.1
9.9
9
But not allow 1.11 or 9.97 or 9,7
Can someone help me?
I tried this '/[0-9]+(\.[0-9]?)?/'
but it still allows 1.11
I am trying to make a regex to allow the following
1
1.1
9.9
9
But not allow 1.11 or 9.97 or 9,7
Can someone help me?
I tried this '/[0-9]+(\.[0-9]?)?/'
but it still allows 1.11
This one should work
'/^\d+(?:\.\d)?$/'
You were close with your example, just needed to declare the beginning and end of string.
Your regex does match the pattern you describe but it fails to exclude the pattern you do not want to match. The 1.1
part in 1.11
matches your regex. To exclude 1.11
you can add to your regex that the string has to end after the first decimal: ^\d+(\.\d)?$
.
\d
matches any digit; you have to escape .
because otherwise it matches any character; and $
means 'end of string'. For quick reference you can check this.
Quite logically the problem also happens at the start of the regex, yours surely matches a1.1
. The special character ^
means 'start of string'.
A regex matching your needs would then be:
^\d+(\.\d)?$
'/\A\d[.]\d\z/'
\A : Start of string
\d : Any digit
[.] : A Single character '.'
\d : Any digit
\z : End of string