【发布时间】:2015-10-25 14:54:54
【问题描述】:
我想对格式化字符串进行标记(非常类似于 printf),我想我只是缺少一点点:
- %[number][one letter ctYymd] 应成为token²
- $1...$10 将成为代币
- 其他所有内容(普通文本)都成为标记。
我在the regExp simulator 中走得很远。这看起来应该这样做:
²更新:现在使用 # 而不是 %。 (windows命令行参数少麻烦)
这并不可怕,如果你专注于三个部分,通过管道连接(作为非此即彼),所以基本上它只是三个匹配。由于我想从头到尾匹配,所以我将东西包裹在 /^...%/ 中,并被一个可能重复 1 次或多次的不匹配组 (?:... 包围:
$exp = '/^(?:(%\\d*[ctYymd]+)|([^$%]+)|(\\$\\d))+$/';
我的来源仍然没有提供:
$exp = '/^(?:(%\\d*[ctYymd]+)|([^$%]+)|(\\$\\d))+$/';
echo "expression: $exp \n";
$tests = [
'###%04d_Ball0n%02d$1',
'%03d_Ball0n%02x$1%03d_Ball0n%02d$1',
'%3d_Ball0n%02d',
];
foreach ( $tests as $test )
{
echo "teststring: $test\n";
if( preg_match( $exp, $test, $tokens) )
{
array_shift($tokens);
foreach ( $tokens as $token )
echo "\t\t'$token'\n";
}
else
echo "not valid.";
} // foreach
我得到了结果,但是:匹配有问题。第一个 %[number][letter] 从不匹配,因此其他匹配双精度:
expression: /^((%\d*[ctYymd]+)|([^$%]+)|(\$\d))+$/
teststring: ###%04d_Ball0n%02d$1
'$1'
'%02d'
'_Ball0n'
'$1'
teststring: %03d_Ball0n%02x$1%03d_Ball0n%02d$1
not valid.teststring: %3d_Ball0n%02d
'%02d'
'%02d'
'_Ball0n'
teststring: %d_foobardoo
'_foobardoo'
'%d'
'_foobardoo'
teststring: Ball0n%02dHamburg%d
'%d'
'%d'
'Hamburg'
【问题讨论】: