Created
May 8, 2014 08:21
-
-
Save kobachi/94aea9b03b2c2ea999ce to your computer and use it in GitHub Desktop.
PatternReplacer.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PatternReplacer implements Function<String, String>(){ | |
private Pattern pattern; | |
private String replacement; | |
private String cachedText; | |
private Matcher cachedMatcher; | |
public PatternReplacer(String pattern, String replacement){ | |
this.pattern = Pattern.compile(pattern); | |
this.replacement = replacement; | |
} | |
public PatternReplacer(Pattern pattern, String replacement){ | |
this.pattern = patternl | |
this.replacement = replacement; | |
} | |
protected Matcher getMatcher(@Nonnull String text){ | |
if(cachedText == null || !cachedText.equals(text) || cachedMatcher == null){ | |
cachedText = text; | |
cachedMatcher = pattern.matcher(text); | |
} | |
return cachedMatcher; | |
} | |
public boolean matches(String text){ | |
if(text == null){ | |
return false; | |
} | |
return getMatcher(text).matches(); | |
} | |
@Override | |
public String apply(String text){ | |
if(text == null){ | |
return null; | |
} | |
return getMatcher(text).replaceAll(replacement); | |
} | |
public Pattern getPattern(){ | |
return pattern; | |
} | |
public void setPattern(Pattern value){ | |
pattern = value; | |
cachedText = null; | |
cachedMatcher = null; | |
} | |
public String getReplacement(){ | |
return replacement; | |
} | |
public void setReplacement(String value){ | |
replacement = value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Replace <br> tag into CRLF