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:
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:
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);
?>
cat filename | php whatever-you-called-it.phpThis is a quick and dirty approach that converts all patterns to string type printf format
0 Comments
Add Comment