Skip to content

Instantly share code, notes, and snippets.

@kobachi
Created May 8, 2014 08:21
Show Gist options
  • Save kobachi/94aea9b03b2c2ea999ce to your computer and use it in GitHub Desktop.
Save kobachi/94aea9b03b2c2ea999ce to your computer and use it in GitHub Desktop.
PatternReplacer.java
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;
}
}
@kobachi
Copy link
Author

kobachi commented May 8, 2014

Replace <br> tag into CRLF

PatternReplacer pr = new PatternReplacer("<[Bb][Rr]\\W*/?>", "\r\n");

if(pr.matches(text)){
    text = pr.apply(text);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment