利用正则表达式根据自己的要求替换

前端之家收集整理的这篇文章主要介绍了利用正则表达式根据自己的要求替换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

public class Main {
public static void main(String[] args) {
String msg = "Java编程思想 :). 大学生就业 ,Java实习";
msgProcessor process = new msgProcessor();
process.setMsg(msg);
FilterChain filter = new FilterChain();
filter.addFilter(new FindAndReplaceFilter()).addFilter(
new ReplaceFilter());
process.setFc(filter);
System.out.println(process.getMsg());
}
}

public interface Filter {
public String doFilter(String str);
}

import java.util.ArrayList;
import java.util.List;

public class FilterChain {
List filters=new ArrayList();

public FilterChain addFilter(Filter filter){
filters.add(filter);
return this;
}
public String doFilter(String msg){
for(Filter f : filters){
msg=f.doFilter(msg);
}
return msg;
}
}

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FindAndReplaceFilter implements Filter {
@Override
public String doFilter(String str) {
// 第一步首先定义一个应被过滤的字符数组即正则表达式
String[] msg = new String[] { "大学生","就业","呵呵" };
// 第二步将正则表达式编译到模式中
Pattern p = null;
for (String s : msg) {
p = Pattern.compile(s);
// 第三步 创建匹配给定输入与此模式的匹配器
Matcher m = p.matcher(str);
// 第四步方法扫描输入序列以查找与该模式匹配
if (m.find())
str = str.replace(s," ");
}
return str;
}

}

public class ReplaceFilter implements Filter {
@Override
public String doFilter(String str) {
str=str.replace("<","[");
return str;
}
}

public class msgProcessor { private String msg; FilterChain fc; public FilterChain getFc() { return fc; } public void setFc(FilterChain fc) { this.fc = fc; } public String getMsg() { return fc.doFilter(msg); } public void setMsg(String msg) { this.msg=msg; } }

猜你在找的正则表达式相关文章