我想正则表达式/替换下面的一组:由有越来越多的正则表达式替换
%0 %1 %2
换句话说
[something] [nothing interesting here] [boring.....]
,这是建立与[]
任何表述将成为%
其次是越来越多的数字...
是否有可能立即与正则表达式?
我想正则表达式/替换下面的一组:由有越来越多的正则表达式替换
%0 %1 %2
换句话说
[something] [nothing interesting here] [boring.....]
,这是建立与[]
任何表述将成为%
其次是越来越多的数字...
是否有可能立即与正则表达式?
这是可能的正则表达式在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'
不是直接的,因为你描述的是一个程序组件。我认为Perl可能会允许这个,尽管它的qx操作符(我认为),但一般来说,你需要遍历字符串,应该很简单。
answer = ''
found = 0
while str matches \[[^\[\]]\]:
answer = answer + '%' + (found++) + ' '
您可以使用Regex.Replace
,它有一个handy overload that takes a callback:
string s = "[something] [nothing interesting here] [boring.....]";
int counter = 0;
s = Regex.Replace(s, @"\[[^\]]+\]", match => "%" + (counter++));
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中,但在课堂上包裹起来有点整洁。
您使用的是哪种正则表达式引擎/实用程序? – kzh 2010-12-06 14:31:31
这是不可能使用正则表达式。你使用什么实现? (这应该是哪个实现....?=)) – Jens 2010-12-06 14:31:39