-2

I want a regular expression like first letter should be + or - or number and if it is - or + followed letter should be number and also allow 2 decimal point. If enter + or - followed letter could not be . (dot).

I am trying with following reg ex but few condition is not working properly.

/^[+-]*\d*\.?\d?\d?/g;
Patrick Q
  • 6,373
  • 2
  • 25
  • 34
Alfiza malek
  • 994
  • 1
  • 14
  • 36

1 Answers1

2

You basically want your string to begin with a number, that can be prefixed by a plus or minus and has at most 2 decimal points.

The regex for this looks like this:

/^[+-]?\d+(?:\.\d{1,2})?$/
  1. [+-]?The regex allows a string to start with a + or minus sign, but not necessarily.
  2. \d+It is then followed by a number.
  3. (?:\.\d{1,2})? That number may have a dot with up to two following numbers. (precision of 2)
Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25
  • Before someone comments: Special chars do not need to be escaped in or groups (`[]`) – Philipp Maurer Mar 19 '18 at 13:41
  • Not working.It allowing me 1+++,1----,1.... and do not allow to add + or - in front. – Alfiza malek Mar 19 '18 at 13:54
  • @Rafikmalek Because those strings are correcty accordingly to your question. The string starts with a number. The `+++`, `---` and `...` part is grouped by the `.*` (4.) and cannot be determined by me, because you did not specify it in your question. Adjust 4. accodingly to your specifications to rule those answers out. – Philipp Maurer Mar 19 '18 at 13:57
  • No should strat with number or + or - – Alfiza malek Mar 19 '18 at 13:58
  • @Rafikmalek It starts with the number 1 :-) – Philipp Maurer Mar 19 '18 at 13:58
  • and there should be only one time existence of + - and .IF you are using + you cant use - sign and vise versa. – Alfiza malek Mar 19 '18 at 13:59
  • @Rafikmalek Well, i removed the part after the numbers. Now only numbers are allowed. Hope thats what you ment :-) If you want to use strings afterwards just add `[^+-.]` before the `$` in the regex. – Philipp Maurer Mar 19 '18 at 14:01