Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

java - Regex to match any number (Real, rational along with signs)

I've written a regex to match any number:

  • Positive and Negative
  • Decimal
  • Real Numbers

The following regex does well but there's one drawback

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

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

The regex should work with the following inputs

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

and shouldn't match the following inputs

+

-

+.

-.

.

Here is the answer by tchrist, works perfectly.

(?:(?i)(?:[+-]?)(?:(?=[.]?[0-9])(?:[0-9]*)(?:(?:[.])(?:[0-9]{0,}))?)(?:(?:[E])(?:(?:[+-]?)(?:[0-9]+))|))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want something that looks like a C float, here’s how to tickle Perl into coughing out a regex that does that, using the Regexp::Common module from CPAN:

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

You can tune that a bit if you want, but that gives you the basic idea.

It’s really remarkably flexible. For example, this spits out a pattern for base-2 real numbers taht allow 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 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}

Making it really to customize it for whatever you want. And yes, of course you can use these patterns in Java.

Enjoy.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...