Akom's Tech Ruminations

Various tech outbursts - code and solutions to practical problems

Converting .NET String.format pattern to Java with a regular expression Code and Hacks

Posted by Admin • Monday, September 10. 2012 • Category: Code and Hacks

For this exercise in futility, I want to accomplish the following:

From .NET: "Hello, {0} Today is the {1} day"  
To JAVA: "Hello, {%1$s} Today is the {%2$s} day"


Note that a simple regex would work here if it weren't for the zero-based indexes. We need to increment the number as well do a pattern replace. Since I'm comfortable with PHP, I took a sample from preg_replace_callback description and modified it accordingly:



<?php
/  Convert all {0} style format patterns to %1$s style patterns.   /
$fp = fopen("php://stdin", "r") or die("can't read stdin");
while (!feof($fp)) {
    $line = fgets($fp);
    $line = preg_replace_callback(
        '/{([0-9]+)}/',
        create_function(
            // single quotes are essential here,
            // or alternative escape all $ as \$
            '$matches',
            'return \'%\'. (intval($matches[1]) + 1) . \'$s\';'
        ),
        $line
    );
    echo $line;
}
fclose($fp);
?>

 
To use it, just pipe your text through it, eg:
cat filename | php whatever-you-called-it.php
This is a quick and dirty approach that converts all patterns to string type printf format

0 Trackbacks

  1. No Trackbacks

0 Comments

Display comments as (Linear | Threaded)
  1. No comments

Add Comment


You can use [geshi lang=lang_name [,ln={y|n}]][/geshi] tags to embed source code snippets.
Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
Standard emoticons like :-) and ;-) are converted to images.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

What is the primary language of this blog? (Anti-SPAM question)


Submitted comments will be subject to moderation before being displayed.