Perl正则表达式提取浮点数 [英] Perl regex to extract floating number

查看:70
本文介绍了Perl正则表达式提取浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要修改某人的 Perl 脚本,我对 Perl 完全不熟悉.

I need to modify someone's Perl script, and I am not familiar with Perl at all.

有一个标量变量$var,它的值是一个浮点数,可能后面跟着垃圾.我需要提取浮点数.

There is a scalar variable $var, whose value is a floating point number possibly followed by junk. I need to extract the floating point number.

数字采用非指数格式:DDD[.DDD],没有符号.

The number is in non-exponential format: DDD[.DDD], and has no sign.

小数部分可能丢失.整数部分没有丢失(.123 只是垃圾)

Fractional part may be missing. Integer part is not missing (.123 is just junk)

如果变量以垃圾开头(特别是符号或小数点),我需要提取空字符串.

If the variable starts with junk (in particular, sign or decimal point), I need to extract empty string.

示例:

-123.456 ==> ""
123. ==> "123"
123.456.789 ==> "123.456"
123.456junk ==> "123.456"
123junk ==> "123"
123.junk ==> "123"     # strip the dot if no fraction
.123 ==> ""
junk ==> ""
000.000 ==> "000.000"

有人可以提供解决方案吗,我想应该是:$var =~ s/REGEX_EXPRESSION,但我不知道 REGEX_EXPRESSION 应该是什么.

Could someone provide a solution, I guess it should be: $var =~ s/REGEX_EXPRESSION, but I cannot figure out what REGEX_EXPRESSION should be.

谢谢.

推荐答案

随着您的更新,您需要的表达式是:

Following your update, the expression you need is:

^\d+(?:\.\d+)?

  • ^\d+ 匹配字符串开头的数字.
  • (?: 非捕获组的开始.
  • \.\d+ 匹配文字 .,后跟数字.
  • )? 关闭非捕获组使其成为可选的.
    • ^\d+ Match digits at start of string.
    • (?: Start of non capturing group.
    • \.\d+ Match a literal ., followed by digits.
    • )? Close non capturing group making it optional.
    • 此处检查表达式.

      Perl 示例:

      $var = "123.456.789";
      print "old $var\n";
      $var =~ /(^\d+(?:\.\d+)?)/;
      print "new $1\n";
      

      打印:

      old 123.456.789
      new 123.456
      

      这篇关于Perl正则表达式提取浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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