001/* 002 * Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew. 003 * 004 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 005 * 006 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 007 * 008 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 009 */ 010package org.kew.rmf.transformers; 011 012import java.util.regex.Pattern; 013 014/** 015 * A generic transformer that searches for all occurrences of a regular expression pattern (regEx) 016 * {@link #pattern} in a string and replaces each with a string {@link #replacement}. 017 * <br/> 018 * <code>replacement</code> can be a normal string, or can include match groups like <code>$1</code>. 019 * <br/> 020 * It takes two optional parameters, {@link #removeMultipleWhitespaces} (default true) and 021 * {@link #trimIt} (default true) 022 */ 023public class RegexTransformer implements Transformer { 024 025 private Pattern pattern; 026 private String replacement = ""; 027 private boolean removeMultipleWhitespaces = true; 028 private boolean trimIt = true; 029 030 @Override 031 public String transform(String s) { 032 s = pattern.matcher(s).replaceAll(getReplacement()); 033 034 if (this.removeMultipleWhitespaces) { 035 s = SqueezeWhitespaceTransformer.MULTIPLE_WHITESPACE.matcher(s).replaceAll(" "); 036 } 037 038 if (this.trimIt) { 039 s = s.trim(); 040 } 041 042 return s; 043 } 044 045 public Pattern getPattern() { 046 return pattern; 047 } 048 public void setPattern(String pattern) { 049 this.pattern = Pattern.compile(pattern); 050 } 051 052 public String getReplacement() { 053 return replacement; 054 } 055 public void setReplacement(String replacement) { 056 this.replacement = replacement; 057 } 058 059 public boolean isRemoveMultipleWhitespaces() { 060 return removeMultipleWhitespaces; 061 } 062 public void setRemoveMultipleWhitespaces(boolean removeMultipleWhitespaces) { 063 this.removeMultipleWhitespaces = removeMultipleWhitespaces; 064 } 065 066 public boolean isTrimIt() { 067 return trimIt; 068 } 069 public void setTrimIt(boolean trimIt) { 070 this.trimIt = trimIt; 071 } 072}