1

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?

Kobi
  • 130,553
  • 41
  • 252
  • 283
Andy M
  • 5,759
  • 6
  • 46
  • 95

4 Answers4

4

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'
Michael Low
  • 23,771
  • 15
  • 77
  • 117
3

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++));
Kobi
  • 130,553
  • 41
  • 252
  • 283
2

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++) + ' '
Andrew White
  • 51,542
  • 18
  • 111
  • 135
  • Yeah, so you it wouldn't possible to make it with regex only ? – Andy M Dec 06 '10 at 14:36
  • Regular expressions are used for matching / parsing. How would you replace anything using just regular expressions? – aioobe Dec 06 '10 at 14:36
  • @Andy M: No, this is not possible with regular expressions only. You need some additional control strucutres. – jwueller Dec 06 '10 at 14:37
1

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.

Paul Dixon
  • 287,944
  • 49
  • 307
  • 343