【问题标题】:PHP RegEx - match to the end of a stringPHP RegEx - 匹配到字符串的结尾
【发布时间】:2010-10-19 04:15:48
【问题描述】:

如果我的字符串是

Size : 93743 bytes Time elapsed (hh:mm:ss.ms): 00:00:00.156

如何匹配(hh:mm:ss.ms): 之后出现的值?

00:00:00.156

如果值后面有更多字符,我知道如何匹配,但后面没有更多字符,我不想包含大小信息。

【问题讨论】:

    标签: php regex


    【解决方案1】:

    像这样:

    <?php
    $text = "Size : 93743 bytes Time elapsed (hh:mm:ss.ms): 00:00:00.156";
    
    # match literal '(' followed by 'hh:mm:ss.ms' followed by literal ')'
    # then ':' then zero or more whitespace characters ('\s')
    # then, capture one or more characters in the group 0-9, '.', and ':'
    # finally, eat zero or more whitespace characters and an end of line ('$')
    if (preg_match('/\(hh:mm:ss.ms\):\s*([0-9.:]+)\s*$/', $text, $matches)) {
        echo "captured: {$matches[1]}\n";
    }
    ?>
    

    这给出了:

    captured: 00:00:00.156
    

    【讨论】:

      【解决方案2】:

      $ 将正则表达式锚定到字符串的末尾:

      <?php
      $str = "Size : 93743 bytes Time elapsed (hh:mm:ss.ms): 00:00:00.156";
      
      $matches = array();
      
      if (preg_match('/\d\d:\d\d:\d\d\.\d\d\d$/', $str, $matches)) {
        var_dump($matches[0]);
      }
      

      输出:

      string(12) "00:00:00.156"
      

      【讨论】:

      • 00:00:00:1 或 00:00:00:22 怎么样?
      • @Amarghosh 问题并未表明其中任何一个都是可能的输入;我假设在这些情况下格式为...00:100 和...00:220。
      • 这仍然不起作用,不确定字符串后面是否有某种额外的空格或什么......是的,格式是...00:100 - 也就是说@987654329 @ 告诉 preg_match 它应该停止查看该点,还是继续查看直到字符串的末尾?我想我需要在最后一个 \d 之后停止比赛
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      • 2014-03-03
      • 1970-01-01
      • 2014-09-21
      • 2021-11-06
      • 1970-01-01
      相关资源
      最近更新 更多