正则表达式可以匹配任何数字(实数,有理数和符号) [英] Regex to match any number (Real, rational along with signs)

查看:128
本文介绍了正则表达式可以匹配任何数字(实数,有理数和符号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个正则表达式来匹配任何数字:

I've written a regex to match any number:

  • 正面和负面
  • 十进制
  • 实数

以下正则表达式效果很好,但有一个缺点

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

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

并且不应与以下输入内容匹配

and shouldn't match the following inputs

+

-

+.

-.

.

这是tchrist的回答,很完美.

(?:(?i)(?:[+-]?)(?:(?=[.]?[0-9])(?:[0-9]*)(?:(?:[.])(?:[0-9]{0,}))?)(?:(?:[E])(?:(?:[+-]?)(?:[0-9]+))|))

推荐答案

如果您想要看起来像C浮点数的方法,则可以使用

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.

它确实非常灵活.例如,这为以2为底的实数倒出了一个模式,即允许每三个位置使用逗号:

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}

使它真正针对您想要的内容进行自定义.是的,您当然可以在Java中使用这些模式.

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

享受.

这篇关于正则表达式可以匹配任何数字(实数,有理数和符号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆