3

I am trying enhance the given answer on another post:

^[1-9]\d*(?:\.[05])?$

Breakup:

^        # Start of input
[1-9]    # match digit 1 to 9
\d*      # match 0 or more of any digits
(?:      # start of non-capturing group
\.       # match a decimal
[05]     # followed by digit 0 or 5
)?       # end non-capturing group. (? makes this group optional)
$        # End of input

Only this time the regex needs to accept 0,5 or 0.5 and increments of 0,5 or 0.5

The number zero is the only one that can't be matched.

Already tried:

(?!0).{1}|^[1-9]\d*(?:(,|\.)[05])?$

and

[^0]|^[1-9]\d*(?:(,|\.)[05])?$

Can you help please?

abligh
  • 24,573
  • 4
  • 47
  • 84

3 Answers3

2

You can use

^(?!0$)\d+(?:[,.][05])?$

See demo

This will match your required numbers and will exclude a 0-only number thanks to the look-ahead at the beginning.

Main changes:

  • \d+ - replaced [1-9]\d* to allow a 0 as the integer part
  • [,.] - replace \. to allow a comma as a decimal separator.
  • The lookahead adds a 0-number exception.

The lookahead can be enhanced to disallow 0.000-like input:

^(?!0+(?:[,.]0+)?$)\d+(?:[,.][05])?$

See another demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

You can use this regex:

^(?:5|[1-9]\d*[05])(?:[,.][05])?$

RegEx Demo

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

This should do it:

^(?!0*$)0?\d*([,.]5)?$

See live demo.

This uses ^\d*([,.]5)?$ to match what you want, and uses ^(?!0*([,.]0*)?$) to exclude zero in all its forms, ie it won.t match 0, 000 etc

Bohemian
  • 412,405
  • 93
  • 575
  • 722