用jakarta-oro实现正则表达式的一个简单类

package jakarta_oro;

import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;

/**
 *@author:jackey
 *@descript:正则表达式封装类
 */
public class BaseOro {
 private PatternCompiler compiler = null;

 private Pattern pattern = null;

 private PatternMatcher matcher = null;

 private MatchResult results = null;
 
 private String strs="[a-z]*[A-Z]*";
 private String nums="[0-9]*";
 private String symbol_by_one="([a-z]{1}|[A-Z]{1}|[0-9]{1})";

 public BaseOro() {
  compiler = new Perl5Compiler();
  matcher = new Perl5Matcher();
 }

 /**
  * 判断sourceStr中是否包含通配符patternStr
  */
 public boolean contains(String sourceStr, String patternStr)
   throws MalformedPatternException {
  boolean returnFlag = false;
  pattern = compiler.compile(patternStr);
  if (matcher.contains(sourceStr, pattern)) {
   returnFlag = true;
  }
  return returnFlag;

 }
 /**
  * 返回sourceStr中查找到的通配符patternStr
  */
 public String getContains(String sourceStr, String patternStr) throws MalformedPatternException{
  String returnStr=null;
  patternStr=this.setUp(patternStr);
  pattern = compiler.compile(patternStr);
  if (matcher.contains(sourceStr, pattern)) {
   results=matcher.getMatch();
   //此处只取一个匹配的值
   returnStr=results.group(0);
  }
  return returnStr;
  
 }
 /**
  * 在sourceStr中用replaceStr替换查找到的patternStr
  */
 public String blurReplace(String sourceStr, String patternStr,String replaceStr){
  String newStr="";
  String beReplaceStr="";
  try {
   beReplaceStr=this.getContains(sourceStr,patternStr);
   newStr=sourceStr.replace(beReplaceStr,replaceStr);
  } catch (MalformedPatternException e) {
   e.printStackTrace();
  }
  
  
  return newStr;
 }
 /**
  * 将pattern转换成正则表达式识别的语法
  * @param pattern
  * @return
  */
 private String setUp(String pattern){
  String str="";
  char[] ch=pattern.toCharArray();
  for (char c : ch) {
   if ('*'==c) {
    str=str+strs+nums;
   } else if('?'==c) {
    str=str+symbol_by_one;
   }else{
    str=str+c;
   }
  }
  return str;
 }

 public static void main(String[] args) throws MalformedPatternException {
  BaseOro bo = new BaseOro();
  System.out.println(bo.blurReplace("bccd278ab", "8?","222"));//模糊替换
  System.out.println(bo.getContains("aabbccd","a???c"));//查找
  System.out.println(bo.getContains("aabbccd","a*c"));//查找
  
 }

}



你可能感兴趣的:(apache,C++,c,正则表达式,C#)