Akom's Tech Ruminations

Various tech outbursts - code and solutions to practical problems
Code and Hacks

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

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:

/  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(
            // single quotes are essential here,
            // or alternative escape all $ as \$
            'return \'%\'. (intval($matches[1]) + 1) . \'$s\';'
    echo $line;

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


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

Add Comment

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
You can use [geshi lang=lang_name [,ln={y|n}]][/geshi] tags to embed source code snippets.
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.

Markdown format allowed

Submitted comments will be subject to moderation before being displayed.