【发布时间】: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
如果值后面有更多字符,我知道如何匹配,但后面没有更多字符,我不想包含大小信息。
【问题讨论】:
如果我的字符串是
Size : 93743 bytes Time elapsed (hh:mm:ss.ms): 00:00:00.156
如何匹配(hh:mm:ss.ms): 之后出现的值?
00:00:00.156
如果值后面有更多字符,我知道如何匹配,但后面没有更多字符,我不想包含大小信息。
【问题讨论】:
像这样:
<?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
【讨论】:
$ 将正则表达式锚定到字符串的末尾:
<?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 怎么样?
...00:100 和...00:220。
...00:100 - 也就是说@987654329 @ 告诉 preg_match 它应该停止查看该点,还是继续查看直到字符串的末尾?我想我需要在最后一个 \d 之后停止比赛