在制作模板内容输出时,很经常会使用之类的占位符,用正则的方式很方便替换这个内容,工作中只接触到java、php、js,三种语言的简单的实现方式:
java版
import java.util.hashmap;
import java.util.map;
import java.util.regex.matcher;
import java.util.regex.pattern;
public class testrex {
public static void main(string[] args) {
map map = new hashmap();
map.put(name, penngo);
map.put(date, 2013-01-17);
pattern p = pattern.compile();
string str = , hello ;
matcher m = p.matcher(str);
stringbuffer sb = new stringbuffer();
boolean result = m.find();
while (result) {
string key = m.group(1);
string value = map.get(key);
m.appendreplacement(sb, value);
result = m.find();
}
m.appendtail(sb);
system.out.println(sb.tostring());
}
}
php版
'penngo', 'date'=>'2013-01-17');
function replacestr($key, $data){
return $data[$key];
}
$str = ', hello ';
$str = preg_replace(//ise, replacestr('\\1', \$data), $str);
echo $str;
?>
js版
var date = {'name':'penngo', 'date':'2013-01-17'};
var str = ', hello ';
str = str.replace(//g, function($0, $1){
var value = date[$1];
return value;
});www.2cto.com
document.write(str);
运行结果输出:
2013-01-17, hello penngo
http://www.bkjia.com/phpjc/477810.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/477810.htmltecharticle在制作模板内容输出时,很经常会使用%=%之类的占位符,用正则的方式很方便替换这个内容,工作中只接触到java、php、js,三种语言的简单...