Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's wrong with this regular expression (if else regex)

What I want is, there is a textbox with maximum length of 5. The values allowed are..

  1. any integer // for example 1, 3, 9, 9239 all are valid
  2. real number, with exaclty one point after decimal // eg. 1.2, 93.7 valid and 61.37, 55.67 invalid
  3. it is also allowed to enter only decimal and a digit after that, that is .7 is valid entry (would be considered as 0.7)

I found this page, http://www.regular-expressions.info/refadv.html
So what I thought is that

  1. There is a digit
  2. If there is a digit and a decimal after that, there must be one number after that
  3. If there is no digit there must be a decimal and a digit after that

So, the regex I made is..

a single digit one or more => /d+  
an optional decimal point followed by exactly one digit => (?:[.]\d{1})?  
if first condition matches => (?(first condition) => (?((?<=\d+)  
then, match the option decimal and one exact digit =>(?((?<=\d+)(?:[.]\d{1})?  
else => |
find if there is a decimal and one exact digit => (?:[.]\d{1}){1}  
check the whole condition globally => /gm

overall expression =>

(?(?<=\d+)(?:[.]\d{1}){1}|(?:[.]\d{1}){1})+/gm

But it doesn't outputs anything..
Here's the fiddle

http://jsfiddle.net/Fs6aq/4/

ps: the pattern1 and pattern2 there, are related to my previous question.

like image 514
Razort4x Avatar asked Oct 06 '22 16:10

Razort4x


2 Answers

Maybe you are complicating things too much. I did a quick test and unless I'm missing something this regex seems to work fine:

/^\d*\.?\d$/

Demo: http://jsbin.com/esihex/4/edit

Edit: To check the length you can do it without regex:

if ( value.replace('.','').length <= 5 && regex.test( value ) ) {
  ...
}

Notice that I used replace to remove the dots so they don't count as characters when getting the length.

like image 61
elclanrs Avatar answered Oct 10 '22 01:10

elclanrs


You can try the following pattern:

/^\d{0,4}\.?\d$/

It seems to fulfil all your requirements:

> /^\d{0,4}\.?\d$/.test(".4")
  true
> /^\d{0,4}\.?\d$/.test(".45")
  false
> /^\d{0,4}\.?\d$/.test("1234.4")
  true
> /^\d{0,4}\.?\d$/.test("12345.4")
  false
> /^\d{0,4}\.?\d$/.test("12345")
  true
> /^\d{0,4}\.?\d$/.test("123456")
  false

This pattern assumes that the number can have a maximum of five digits and an optional decimal point.

If the maximum length of five includes the optional decimal point then the pattern is slightly more complex:

/^(?:\d{1,5}|\d{0,3}\.\d)$/

The first part of the group deals with integer numbers of the required length, the second option of the group deals with real numbers which maximum length (including the decimal point) is five.

like image 38
Vicent Avatar answered Oct 10 '22 03:10

Vicent