duanpie2834 2012-01-06 23:11
浏览 212
已采纳

为什么preg_match匹配最后一个子模式而不是第一个?

I am trying to match the first hexadecimal address from a line that can contain many hexadecimal addresses, but instead I get the last.

My request is:

preg_match('%.*(0x[0-9a-f]{8}){1}.*%', $v, $current_match);

where the $v is a string like:

Line: 2 libdispatch.dylib 0x36eaed55 0x36eae000 + 3413

I would want to get 0x36eaed55, but my regular expression for $current_match[1] returns 0x36eae000 instead.

According to php documentation: $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

  • 写回答

4条回答 默认 最新

  • donglu8334 2012-01-06 23:20
    关注

    The problem is that the * quantifier is greedy by default, so the first .* matches as much as possible while still allowing the entire expression to match. In this case, it means that .* will "gobble up" all of the hexadecimal constants but the last one, as (0x[0-9a-f]{8}){1} still needs to match.

    One solution is to use the non-greedy operator *?. The first constant is found when using the following:

    preg_match('%.*?(0x[0-9a-f]{8}){1}.*?%', $v, $current_match);
    

    However, because you know that $v includes a hexadecimal constant, and you want the first one, then why not simply match against the pattern of the hexadecimal constant?

    preg_match('%0x[0-9a-f]{8}%', $v, $current_match);
    

    Even if you wanted the second, third, fourth, ... hexadecimal constant, you could use preg_match_all() with the same pattern:

    preg_match_all('%0x[0-9a-f]{8}%', $v, $all_matches, PREG_PATTERN_ORDER);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?