(s)printf FORMAT字符串的权威正则表达式

Ekk*_*ner 6 regex perl printf

我想回答这个问题

要获得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;
}
Run Code Online (Sandbox Code Playgroud)

但我对捕获格式字符串'尾'的冒险/暴力方法感到羞耻.

那么:您可以信任的FORMAT字符串是否有正则表达式?

mob*_*mob 1

可接受的格式在perldoc -f sprintf. 在'%'和 格式字母之间,您可以有:

     (\d+\$)?         # format parameter index (though this is probably
                      # incompatible with the dictionary feature)

     [ +0#-]*         # flags

     (\*?v)?          # vector flag

     \d*              # minimum width

     (\.\d+|\.\*)?    # precision or maximum width

     (ll|[lhqL])?     # size
Run Code Online (Sandbox Code Playgroud)