我正在寻找Perl中与以下所有内容匹配的正则表达式:
12345
12345.67
.23E-10 # A very small number
3.14_15_92 # A very important number
4_294_967_296 # Underscore for legibility
0xff # Hex
0xdead_beef # More hex
0377 # Octal (only numbers, begins with 0)
0b011011 # Binary
我当前的正则表达式是([\d\.a-z_A-Z-]*)
,但我匹配太多东西......
更新
我有一个正则表达式,但我希望将它们混合在一起。
(\d*)
(\d*(?:(?=\d*)\.\d*))
(\d*(?:(?=\d*)\.\d*)(?:E?(?=[-|\d]*)-?\d*))
(\d*\.?(?:\d{0,3}_?)*)
(0x([a-zA-Z]*_?)*)
((?:\d*[a-zA-Z]*)*)
答案 0 :(得分:2)
查看Regexp::Common
,特别是Regexp::Common::number
。它将为大多数人提供解决方案。
use Regexp::Common qw /number/;
while (<>) {
/^$RE{num}{int}$/ and print "Integer\n";
/^$RE{num}{real}$/ and print "Real\n";
/^$RE{num}{real}{-base => 16}$/ and print "Hexadecimal real\n";
}
答案 1 :(得分:1)
我最终得到了以下正则表达式:
\b((?:0x[a-zA-Z_]+)|(?:0[a-zA-Z\d]+)|(?:\d*\.?\d*E\-?\d*)|(?:\d*\.(?:\d{0,3}_?)*)|(?:\d+)|(?:\d*\.\d+))\b
我确定它并不完美,但是它可以胜任。