Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for fixed length floating point number

I am using this regular expression to match 8 digits signed floating point number.

  string exp= "12345678";
  string regEx1="^([-+]?[(\\d+\\.?(\\d+)?)]{1,8})($)";
  Regex topRowRegx = new Regex(regEx1, RegexOptions.IgnoreCase | RegexOptions.Multiline);
  Match matchResult = topRowRegx.Match(exp.Trim());

irrespective of -/+ and . symbols it should match 1 to 8 digits number.

It should match -1.2345678, 123.45678, +12.34, 1.2, 1, 12345678, 1254. There should be at least one digits before decimal and after decimal, if decimal symbol presents.

The above expression working fine but it is failing when I use -/+ or . with 8 digit number. Can you help me how to identify exactly 8 digits and leave remaining symbols count?

UPDATE: Vasili Syrakis answer solved the above problem. Just for curiosity, why this is not giving correct result?

   string exp = "text> -9.9999999 \"some text here\"";
   var resultNumber = Regex.Match(exp, "[-+]?(\\d{1,8}|(?=\\d\\d*\\.\\d+?$)[\\d\\.]{1,9})");
   ("Result:"+resultNumber.ToString()).Dump();
like image 612
PSR Avatar asked Mar 21 '23 04:03

PSR


2 Answers

Altered regex:

^[-+]?(\d{1,8}|(?=\d\d*\.\d+?$)[\d\.]{1,9})$

Escaped version:

^[-+]?(\\d{1,8}|(?=\\d\\d*\\.\\d+?$)[\\d\\.]{1,9})$

Explanation

It will either find an 8 digit number
OR it will find 9 instances of either a period or number... ONLY if there's 1 period separating the numbers. The 9 is to account for the period.

Online demo

http://regex101.com/r/kD1oT6

like image 113
Vasili Syrakis Avatar answered Apr 02 '23 20:04

Vasili Syrakis


Try this regex:

^[+-]?(?:(?=\d+\.\d+$)[\d.]{3,9}|(?=\d+$)\d{1,8})$

Basically it has two regex are OR'ed together. First one is checking for pattern line xx.xx, means digits at the both side of the dot. Which means it can have minimum 3 to maximum 9 in length.

Second one is trying to match the digits xxxx in format. Which means it can have 1 to 8 in length.

You can get more explanation of this regex from this link.

like image 43
Sabuj Hassan Avatar answered Apr 02 '23 20:04

Sabuj Hassan