drnmslpz42661 2018-10-03 00:53
浏览 215
已采纳

PHP正则表达式忽略字符串中的负数

I've looked all over the place, but I can't seem to only return the first positive, real number. So far, I have successfully found how to find the first positive or negative number and also only find the first negative number. Below are the two I did correctly and the one I can't get.

$str1 = "-ABS-.-179.3333es-k15dk825.44f";

1) Find first real number in string:

preg_match("/-?((\.\d+)|(\d+(\.\d+)?))/", $str1, $matches) // <- GOOD!
Expected output: -179.3333
Actual output: -179.3333


2) Find first, negative real number in string:

preg_match("/-((\.\d+)|(\d+(\.\d+)?))/", $str1, $matches) // <- GOOD!
Expected output: -179.3333
Actual output: -179.3333


3) Find first, positive real number in string:

preg_match("/(?<!-)((\.\d+)|(\d+(\.\d+)?))/", $str1, $matches) //<- WRONG!
Expected output: 15
Actual output: 79.3333


Any help is greatly appreciated!

  • 写回答

2条回答 默认 最新

  • dongsha1544 2018-10-03 01:31
    关注

    Try the following and see if it does what you want.

    preg_match_all('/[^\-\d\.]((?:\d+)(?:(?:\.\d+)|(?:\d+)))/', $str1, $matches);
    
    var_dump($matches[1]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化