我想回答this question與權威的正則表達式(S)格式化字符串
要獲得所有Perl的別緻的格式和鍵訪問的散列數據,你 需要(更好的版本的這個)功能:
# sprintfx(FORMAT, HASHREF) - like sprintf(FORMAT, LIST) but accepts
# "%<key>$<tail>" instead of "%<index>$<tail>" in FORMAT to access the
# values of HASHREF according to <key>. Fancy formatting is done by
# passing '%<tail>', <corresponding value> to sprintf.
sub sprintfx {
my ($f, $rh) = @_;
$f =~ s/
(%%) # $1: '%%' for '%'
| # OR
% # start format
(\w+) # $2: a key to access the HASHREF
\$ # end key/index
( # $3: a valid FORMAT tail
# 'everything' upto the type letter
[^BDEFGOUXbcdefginosux]*
# the type letter ('p' removed; no 'next' pos for storage)
[BDEFGOUXbcdefginosux]
)
/$1 ? '%' # got '%%', replace with '%'
: sprintf('%' . $3, $rh->{$2}) # else, apply sprintf
/xge;
return $f;
}
但我很害羞的風險/暴力方法來捕獲格式字符串的'尾巴'。
所以:有格式字符串,你可以信任的正則表達式?
您是否知道''%%'在'sprintf'中不是特例?例如'sprintf('%2%')'會產生字符串''%''。 – 2012-04-18 19:59:33