Convert from "12345678" to "12:34:56:78"

Hi, I'm trying to convert a variable from "12345678" to "12:34:56:78"

How can I manage that?

Search expression:

([0-9]{2})(?!$)

Replacement expression:

$1:

Purpose: The regular expression above finds every pair of neighbouring digits that do not sit at the end of a line, then inserts a colon immediately after.

Caveats: It will convert any run of 8 digits to a colon-delimited quartet of number pairs, but as the expression doesn't take into account any other features the string might possible have, it will also make the same changes to any string where a pair of digits can be found together, e.g.:

"221B Baker Street" → "22:1B Baker Street"

and, running it through a string that's already been parsed once:

"12:34:56:78" → "12::34::56::78"
2 Likes

and if you needed to parameterise the particular chunk size and/or delimiter, you could, of course, use a script action:

Delimited chunks.kmmacros (19 KB)

JavaScript source

(() => {
    'use strict';

    // chunksOf :: Int -> [a] -> [[a]]
    const chunksOf = n => xs =>
        enumFromThenTo(0, n, xs.length - 1)
        .reduce(
            (a, i) => a.concat([xs.slice(i, (n + i))]),
            []
        );

    // enumFromThenTo :: Int -> Int -> Int -> [Int]
    const enumFromThenTo = (x1, x2, y) => {
        const d = x2 - x1;
        return Array.from({
            length: Math.floor(y - x2) / d + 2
        }, (_, i) => x1 + (d * i));
    };

    const
        kme = Application('Keyboard Maestro Engine'),
        kmValue = k => kme.getvariable(k),

        [size, delim, input] = ['chunkSize', 'delimiter', 'inputString']
        .map(kmValue);


    return chunksOf(parseInt(size))(
        input
    ).join(delim);
})();
1 Like

That's fantastic Guys. Thank you for this also quick response.