繁体   English   中英

正则表达式替换越来越多

[英]regex replacement with a increasing number

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

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

通过

%0 %1 %2

换句话说,任何用[]构建的表达式都将成为%后跟一个递增的数字...

使用Regex可以马上做到吗?

C#中的regex可以做到这一点,因为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'

您可以使用Regex.Replace ,它有一个方便的重载,需要进行回调

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

由于您所描述的内容具有程序成分,因此不直接存在。 我认为Perl可以通过它的qx运算符允许它(我认为),但是一般来说,您需要遍历字符串,这应该非常简单。

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

PHP和Perl都支持“回调”替换,使您可以将一些代码挂钩来生成替换。 这是在PHP中使用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

您可以使用全局var和常规函数回调来完成此操作,但是将其包装在类中则更加整洁。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM