越来越多的正则表达式替换

时间:2010-12-06 14:29:57

标签: c# regex string .net-3.5 replace

我想正则表达式/替换以下集:

[something] [nothing interesting here] [boring.....]

通过

%0 %1 %2

换句话说,使用[]构建的任何表达式都将变为%,后跟数字越来越大......

是否可以使用正则表达式立即执行此操作?

4 个答案:

答案 0 :(得分:4)

这可以在C#中使用正则表达式,因为Regex.Replace可以将委托作为参数。

        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'

答案 1 :(得分:3)

您可以使用Regex.Replace,它有handy overload that takes a callback

string s = "[something] [nothing interesting here] [boring.....]";
int counter = 0;
s = Regex.Replace(s, @"\[[^\]]+\]", match => "%" + (counter++));

答案 2 :(得分:2)

不直接,因为您所描述的内容具有程序性组件。我认为Perl可能允许这个虽然它的qx运算符(我认为),但一般来说你需要遍历字符串,这应该非常简单。

answer = ''
found  = 0
while str matches \[[^\[\]]\]:
    answer = answer + '%' + (found++) + ' '

答案 3 :(得分:1)

PHP和Perl都支持'回调'替换,允许您挂钩一些代码来生成替换。以下是使用preg_replace_callback

在PHP中执行此操作的方法
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

你可以使用全局var和常规函数回调来完成这个,但是在课堂上将它包装起来有点整洁。