001/* 002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the Eclipse Public License v1.0 006 * which accompanies this distribution, and is available at 007 * http://www.eclipse.org/legal/epl-v10.html 008 * 009 * Contributors: 010 * bstefanescu 011 * 012 * $Id$ 013 */ 014 015package org.nuxeo.ecm.platform.rendering.wiki.extensions; 016 017import java.util.regex.Matcher; 018import java.util.regex.Pattern; 019 020import org.nuxeo.common.xmap.annotation.XNode; 021import org.nuxeo.common.xmap.annotation.XObject; 022import org.nuxeo.ecm.platform.rendering.wiki.WikiFilter; 023 024/** 025 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 026 */ 027@XObject("filter") 028public class PatternFilter implements WikiFilter { 029 030 @XNode("pattern") 031 protected Pattern pattern; 032 033 @XNode("replacement") 034 protected String replacement; 035 036 public PatternFilter(String pattern, String replacement) { 037 this.pattern = Pattern.compile(pattern); 038 this.replacement = replacement; 039 } 040 041 public String apply(String content) { 042 Matcher matcher = pattern.matcher(content); 043 if (!matcher.find()) { 044 return null; 045 } 046 StringBuffer sb = new StringBuffer(); 047 do { 048 matcher.appendReplacement(sb, replacement); 049 } while (matcher.find()); 050 matcher.appendTail(sb); 051 return sb.toString(); 052 } 053 054}