I would like to regex/replace the following set:
[something] [nothing interesting here] [boring.....]
by
%0 %1 %2
In other words, any expressions that is built with []
will become a %
followed by an increasing number...
Is it possible to do it right away with a Regex?
This is possible with regex in C#, as Regex.Replace
can take a delegate as a parameter.
Regex theRegex = new Regex(@"\[.*?\]");
string text = "[something] [nothing interesting here] [boring.....]";
int count = 0;
text = theRegex.Replace(text, delegate(Match thisMatch)
{
return "%" + (count++);
}); // text is now '%0 %1 %2'
You can use Regex.Replace
, it has a handy overload that takes a callback:
string s = "[something] [nothing interesting here] [boring.....]";
int counter = 0;
s = Regex.Replace(s, @"\[[^\]]+\]", match => "%" + (counter++));
Not directly since what you are describing has a procedural component. I think Perl might allow this though its qx operator (I think) but in general you need to loop over the string which should be pretty simple.
answer = ''
found = 0
while str matches \[[^\[\]]\]:
answer = answer + '%' + (found++) + ' '
PHP and Perl both support a 'callback' replacement, allowing you to hook some code into generating the replacement. Here's how you might do it in PHP with preg_replace_callback
class Placeholders{
private $count;
//constructor just sets up our placeholder counter
protected function __construct()
{
$this->count=0;
}
//this is the callback given to preg_replace_callback
protected function _doreplace($matches)
{
return '%'.$this->count++;
}
//this wraps it all up in one handy method - it instantiates
//an instance of this class to track the replacements, and
//passes the instance along with the required method to preg_replace_callback
public static function replace($str)
{
$replacer=new Placeholders;
return preg_replace_callback('/\[.*?\]/', array($replacer, '_doreplace'), $str);
}
}
//here's how we use it
echo Placeholders::replace("woo [yay] it [works]");
//outputs: woo %0 it %1
You could do this with a global var and a regular function callback, but wrapping it up in class is a little neater.