2010-12-06 32 views
1

我想正則表達式/替換下面的一組:由有越來越多的正則表達式替換

%0 %1 %2 

換句話說

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

,這是建立與[]任何表述將成爲%其次是越來越多的數字...

是否有可能立即與正則表達式?

+2

您使用的是哪種正則表達式引擎/實用程序? – kzh 2010-12-06 14:31:31

+0

這是不可能使用正則表達式。你使用什麼實現? (這應該是哪個實現....?=)) – Jens 2010-12-06 14:31:39

回答

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' 
2

不是直接的,因爲你描述的是一個程序組件。我認爲Perl可能會允許這個,儘管它的qx操作符(我認爲),但一般來說,你需要遍歷字符串,應該很簡單。

answer = '' 
found = 0 
while str matches \[[^\[\]]\]: 
    answer = answer + '%' + (found++) + ' ' 
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++)); 
1

PHP和Perl都支持「回調」更換,讓你上鉤一些代碼,生成的替代品。這裏是你如何與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 

你可以用全局變量和常規功能的回調做這個做在PHP中,但在課堂上包裹起來有點整潔。