正则表达式使用Java String.replaceAll

前端之家收集整理的这篇文章主要介绍了正则表达式使用Java String.replaceAll前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想要替换如下的 java字符串值.下面的代码不起作用.
  1. cleanInst.replaceAll("[<i>]","");
  2. cleanInst.replaceAll("[</i>]","");
  3. cleanInst.replaceAll("[//]","/");
  4. cleanInst.replaceAll("[\bPhysics Dept.\b]","Physics Department");
  5. cleanInst.replaceAll("[\b/n\b]",";");
  6. cleanInst.replaceAll("[\bDEPT\b]","The Department");
  7. cleanInst.replaceAll("[\bDEPT.\b]","The Department");
  8. cleanInst.replaceAll("[\bThe Dept.\b]","The Department");
  9. cleanInst.replaceAll("[\bthe dept.\b]","The Department");
  10. cleanInst.replaceAll("[\bThe Dept\b]","The Department");
  11. cleanInst.replaceAll("[\bthe dept\b]","The Department");
  12. cleanInst.replaceAll("[\bDept.\b]","The Department");
  13. cleanInst.replaceAll("[\bdept.\b]","The Department");
  14. cleanInst.replaceAll("[\bdept\b]","The Department");

实现上述替换的最简单方法是什么?

如果它是您正在使用的功能,则存在问题.每次调用都会再次编译每个正则表达式.最好将它们创建为常量.你可以有这样的东西.
  1. private static final Pattern[] patterns = {
  2. Pattern.compile("</?i>"),Pattern.compile("//"),// Others
  3. };
  4.  
  5. private static final String[] replacements = {
  6. "","/",// Others
  7. };
  8.  
  9. public static String cleanString(String str) {
  10. for (int i = 0; i < patterns.length; i++) {
  11. str = patterns[i].matcher(str).replaceAll(replacements[i]);
  12. }
  13. return str;
  14. }

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