0

I want to validate input (number with decimal optional) in c# with regular expression with following conditions

  1. Max length of should be 4
  2. only positive numbers
  3. decimal is optional Eg valid case :
    1
    12
    123
    1234
    1.23
    12.3
    0

Invalid cases :

  1. All -ive numbers
  2. Length exceeds 4 including decimal(.)

I have created following expression which is working fine but only problem is I am not able to restrict it to 4 max length

here is my regular expression :

^[\+]?(([0-9]+)([\.,]([0-9]+))?|([\.,]([0-9]+))?)$
Mahajan344
  • 2,492
  • 6
  • 39
  • 90
  • 4
    [Here is how it is done](http://stackoverflow.com/questions/32477182/restricting-character-length-in-regular-expression). – Wiktor Stribiżew Apr 15 '16 at 10:49
  • `(?=^[\d\.]{1,4}$)`.. – rock321987 Apr 15 '16 at 10:50
  • A very good tool with "cheatsheet" for testing regular expressions - http://www.regexr.com/ – Dmitri Trofimov Apr 15 '16 at 10:52
  • @HimBromBeere No, it won't because of other conditions already present in OP's regex.. check:- https://regex101.com/r/rJ0dX7/1 – rock321987 Apr 15 '16 at 10:54
  • @rock321987 your regexp also matches `"."` which is clearly not intended. Or `"1..2"` which is not a number either, or `"1.2."` – derpirscher Apr 15 '16 at 11:14
  • @derpirscher please check it..see here :- https://regex101.com/r/rJ0dX7/2.. i think you all are considering my comment as final regex..it needs to be added in OP's regex..my bad..i should have added it – rock321987 Apr 15 '16 at 11:18
  • @rock321987 you should have pointed that out and given the final result that works. – derpirscher Apr 15 '16 at 11:19
  • I guess [`^(?=[+]?.{1,4}$)(?:[+]?([0-9]+([.,][0-9]+)?|([.,][0-9]+)?))$`](https://regex101.com/r/gT3rB1/1) should work (if the `+` is not to be counted in). Surely, the regex can be further improved, but it is not what the question is about. – Wiktor Stribiżew Apr 15 '16 at 11:39

0 Answers0