On Thu 3-Aug-06 9:49am -0600, Jürgen Krämer wrote:

<snipped>

Very nice explanation!  Two minor cosmetic improvements are
(1) to use Vim's line continuation to break up that very
long line and (2) making the regex "very magic" (your use of
comma eliminated 2 escapes, \v eliminates another 13
escapes.  So:

    :%s,\<\(\d\+\)[-/]\(\d\+\)[-/]\%(20\)\?\(\d\d\)\>,\=(submatch(1) < 10 ? '0' 
: '') . submatch(1) . '-' . (submatch(2) < 10 ? '0' : '') . submatch(2) . '-' . 
'20' . submatch(3),

becomes:

    :%s,\v<(\d+)[-/](\d+)[-/]%(20)?(\d\d)>,\=
        \(submatch(1) < 10 ? '0' : '') . submatch(1) . '-' .
        \(submatch(2) < 10 ? '0' : '') . submatch(2) . '-' .
        \'20' . submatch(3)

Also, I see Chip Campbell's interesting alternate suggestion
using printf():

    
:%s/\(\d\{1,2}\)-\(\d\{1,2}\)-\(\d\{2,4}\)/\=printf('%02d\/%02d\/%4d',submatch(1),submatch(2),(submatch(3)
 < 100)? (2000+submatch(3)) : submatch(3))/

Using semi-colon as a slash replacement in substitute (comma
is used by the printf), extending to handle '-' or '/' in
the date to be translated and permitting one digit years (as
in today's 8/3/6):

    :%s;\v(\d{1,2})[-/](\d{1,2})[-/](\d{1,4});
        \\=printf('%02d/%02d/%4d',
            \submatch(1),
            \submatch(2),
            \(submatch(3) < 100)
                \? submatch(3) + 2000
                \: submatch(3))

Finally, I see Tim Chase had another interesting
alternative using substitute():

    
:%s!\<\(\d\{1,2}\)[-/]\(\d\{1,2}\)[-/]\(\d\d\d\d\|\d\d\)\>!\=substitute('0'.submatch(1),
 '.*\(..\)$', '\1', ''). '/'.substitute('0'.submatch(2), '.*\(..\)$', '\1', 
''). '/'.(strlen(submatch(3)) == 4?submatch(3):(submatch(3)[0] == 
'0'?'20'.submatch(3):'19'.submatch(3)))

Only changing the regex to make it very magic and adding
line continuation (and eliminating one set of redundant
parentheses):

    :%s!\v<(\d{1,2})[-/](\d{1,2})[-/](\d\d\d\d|\d\d)>!\=
        \substitute('0'.submatch(1),
            \'.*\(..\)$', '\1', '') . '/' .
        \substitute('0'.submatch(2),
            \ '.*\(..\)$', '\1', '') . '/' .
        \(
            \strlen(submatch(3)) == 4
                \? submatch(3)
                \: submatch(3)[0] == '0'
                    \? '20'.submatch(3)
                    \:'19'.submatch(3)
        \)

Not only does line continuation, IMO, make it easier to read
in scripts, it is also much easier to read in mail.

-- 
Best regards,
Bill

Reply via email to