A regular expression matches any number (Real, rational, together with signs)

I wrote a regular expression to match any number:

  • Positive and negative
  • Decimal
  • Real numbers

The following regex is good, but there is one drawback

([\+\-]{1}){0,1}?[\d]*(\.{1})?[\\d]* 

It is positive for inputs such as + or - . Any pointers would be greatly appreciated. Thanks.

The regular expression should work with the following inputs

5, +5, -5, 0.5, +0.5, -0.5, .5, +.5, -.5

and do not have to match the following inputs

+

-

+.

-.

.

Here is tchrist answer, works great.

 (?:(?i)(?:[+-]?)(?:(?=[.]?[0-9])(?:[0-9]*)(?:(?:[.])(?:[0-9]{0,}))?)(?:(?:[E])(?:(?:[+-]?)(?:[0-9]+))|)) 
+6
source share
3 answers

If you want something similar to a C float, here's how to tickle Perl from a regular expression that does this using Regexp :: Common module from CPAN :

 $ perl -MRegexp::Common -le 'print $RE{num}{real}' (?:(?i)(?:[+-]?)(?:(?=[.]?[0123456789])(?:[0123456789]*)(?:(?:[.])(?:[0123456789]{0,}))?)(?:(?:[E])(?:(?:[+-]?)(?:[0123456789]+))|)) 

You can tweak this a bit if you want, but it gives you the basic idea.

In fact, it is remarkably flexible. For example, this spills out a pattern for real base-2 numbers, allowing commas every three places:

 $ perl -MRegexp::Common -le 'print $RE{num}{real}{-base => 2}{-sep => ","}{-group => 3}' (?:(?i)(?:[+-]?)(?:(?=[.]?[01])(?:[01]{1,3}(?:(?:[,])[01]{3})*)(?:(?:[.])(?:[01]{0,}))?)(?:(?:[E])(?:(?:[+-]?)(?:[01]+))|)) 

The documentation shows that the full possible syntax for the numeric patterns that it can spit out for you is:

 $RE{num}{int}{-base}{-sep}{-group}{-places} $RE{num}{real}{-base}{-radix}{-places}{-sep}{-group}{-expon} $RE{num}{dec}{-radix}{-places}{-sep}{-group}{-expon} $RE{num}{oct}{-radix}{-places}{-sep}{-group}{-expon} $RE{num}{bin}{-radix}{-places}{-sep}{-group}{-expon} $RE{num}{hex}{-radix}{-places}{-sep}{-group}{-expon} $RE{num}{decimal}{-base}{-radix}{-places}{-sep}{-group} $RE{num}{square} $RE{num}{roman} 

Do it really to tune it to whatever you want. And yes, of course, you can use these patterns in Java.

Enjoy.

+5
source

You will need at least one digit, i.e. using + instead of * for \d .

I think you can also remove {1} in several places, as this is implied by default

Similarly, {0,1} can be discarded, and then ?

Providing us with:

 regex = "[+-]?(\\d+|\\d*\\.?\\d+)"; 
+3
source

I think this should do it:

 [+-]?\d*(\.\d+)? 

EDIT:

I improved it so that it does not match the point at -123. but for 123.456

EDIT2:

Thus, it does not correspond only to + or -, you can verify that such a sign must precede either a point or a number, and the point is optional.

 [+-]?(?=[\.?\d])\d*(\.\d+)? 
+1
source

Source: https://habr.com/ru/post/908777/


All Articles