4

This is my regex to check percentage with 2 decimals up to 100

^-?(100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)

but is working only in 99.16 and not like -99.16

How to allow also minus percentage?

mbrc
  • 3,523
  • 13
  • 40
  • 64
  • `(^-?(100([.]0{1,2})?)$)|(^-?[0-9]{1,2}([.][0-9]{1,2})?)`; please, notice `-?` in the second alternative of the expression – Dmitry Bychenko Jun 06 '16 at 10:55
  • You can also use a [group](http://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group): [`^-?(?:100(?:\.00?)?|\d\d?(?:\.\d\d?)?)$`](https://regex101.com/r/pN3rT5/1) – bobble bubble Jun 06 '16 at 12:00

2 Answers2

3

You have two alternatives:

  • special case of 100 precent
  • standard case of 0..99 precent

both alternatives can have minus sign (-):

  (^-?(100([.]0{1,2})?)$)|(^-?[0-9]{1,2}([.][0-9]{1,2})?$)

as a remark, you probably want [0-9] when matching digits not any character treated as digit '\d' which include, say, Persian digits ۰ ۱ ۲ ۳ ۴ ۵ ۶ ۷

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • @Xufox: Nice find! I should not have copied + pasted the *original regex*. – Dmitry Bychenko Jun 06 '16 at 11:08
  • Thank you for fast reply – mbrc Jun 06 '16 at 11:30
  • On your side note: is there a way to make `\d` *not* match Persian digits? – Linus Kleen Jun 06 '16 at 12:24
  • @LinusKleen, it is actually the opposite. By default in Java the character class `\d` will not match non-ASCII digits (such as `۱`; U+06F1) unless you use the [`UNICODE_CHARACTER_CLASS` flag](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/regex/Pattern.html#UNICODE_CHARACTER_CLASS): `"\u06F1".matches("\\d") == false`, `"\u06F1".matches("(?U)\\d") == true` – Marcono1234 Sep 22 '20 at 23:08
2

You've just missed the ^-? in the second option

^-?(100([.]0{1,2})?)$|(^-?\d{1,2}([.]\d{1,2})?)
SCouto
  • 7,808
  • 5
  • 32
  • 49