0

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

melpomene
  • 84,125
  • 8
  • 85
  • 148
Brian
  • 15
  • 7
  • Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer! See also: [ask] – Thomas Ayoub Apr 14 '17 at 14:23
  • 1
    The regex language/tool you are using would also help – silel Apr 14 '17 at 14:24
  • The language is PHP but that doesn't really matter right? – Brian Apr 14 '17 at 14:26
  • 2
    It actually does, there are several types or regex, for example: BRE (Basic Regular Expressions) or ERE (Extended Regular Expressions), and their syntax varies. – silel Apr 14 '17 at 14:44
  • PHP has a list of differences between PCRE an POSIX (which mysql uses and older PHP functions). http://php.net/manual/en/reference.pcre.pattern.posix.php – chris85 Apr 14 '17 at 14:53
  • I think you need `'/^\d(\.\d)?$/D'` – Wiktor Stribiżew Apr 14 '17 at 15:24

4 Answers4

1

This one should work

'/^\d+(?:\.\d)?$/'

You were close with your example, just needed to declare the beginning and end of string.

maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37
1
'/[0-9]{1,}.[0-9]/'

this should also works

RomMer
  • 909
  • 1
  • 8
  • 19
1

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)?$
silel
  • 567
  • 2
  • 10
0
'/\A\d[.]\d\z/'

\A : Start of string

\d : Any digit

[.] : A Single character '.'

\d : Any digit

\z : End of string