sbpya 发表于 2013-2-7 15:38:19

正则表达式速成

匹配规则篇
一、句点符号:.
      句点符号匹配所有字符,包括空格、Tab字符甚至换行符;
      例:正则表达式 b.n  匹配:bon,btn,bin,bbn,bcn等等
 
二、方括号符号:[]
      方括号内指定匹配符号的范围,只能匹配单个字符;
      例:正则表达式 bn  只能匹配:bon,btn,bin
 
三、“或”符号: |
      “|”操作符的基本意义就是“或”运算
       例:  正则表达式 b(o|t|i|oo)n  除了匹配:bon,btn,bin外,还能匹配boon。圆括号()可以用来分组
 
四、连字符:-
       表示一个范围,比如:0到9,a到z   例:{2} 表示2个0到9之间的数字
       如果一个字符的格式是:888-8888-88888,不限于8,只要是数字,是这种格式,正则表达式应该写成:
       {3}\-{4}\-{5}  在这里用\进行转义,如果不转义,则会当成连字符
 
五、匹配字符数量的限制:以下符号用来表示紧靠该符号左边的符号出现的次数:
      *    0次或多次     +   1次或多次   ?   0次或1次     {n}  只能出现正好n次   {n,m}    出现次数在n到m数之间
 
六、非符号:^
    ^用在[]内表示否定的意思,不能是什么字符
    [^A]{5}  表示6个字符,第一个字符是除A以外的任何字符,第二到第六个字符必须是a到z之间的字符
 
七、圆括号和空白符号:
     第三条说过,()是分组符号,而“\s”符号是空白符号,匹配所有的空白字符,包括Tab字符
 
八、常见符号:
      \d   等同于 
      \D   等同于 [^0-9]
      \w   等同于
      \W  等同于  [^A-Z0-9]
      \s    等同于 [\t\n\r\f]
      \S    等同于 [^\t\n\r\f]
 
常规应用篇
一、邮政编码:
    boolean checkPostcode(){

        Pattern p=Pattern.compile("{6}");
        Matcher m=p.matcher(inputStr);

        if (!m.matches()){
           System.out.println("****邮政编码格式不符!*****");
           return false;
        }
        return true;
    }
 
    java.util.regex中有两个类:Pattern和Matcher,Pattern为模板,Matcher为被匹配者。
 
二、Email:
    boolean checkEmail(){

      Pattern p=Pattern.compile("+@(+.){1,2}(com|net|cn|com.cn)");
      Matcher m=p.matcher(inputStr);
 
      if(!m.matches()){
        System.out.println("****电子邮件格式不符!*****");
        return false;
      }
      return true;
   }
 
    注:(com|net|cn|com.cn)只允许这几种后缀的域名,如果实际应用中不限于这几种后缀域名,此处需要改动
 
三、IP地址:
    boolean ipValid(String s) {
         String regex0="(2\\d)" + "|(25)";
         String regex1="1\\d{2}";
         String regex2="\\d";
         String regex3="\\d ";
         String regex="("+regex0+")|("+regex1+")|("+regex2+")|("+regex3+")";
         regex="("+regex+").("+regex+").("+regex+").("+regex+")";
 
         Pattern p=Pattern.compile(regex);
         Matcher m=p.matcher(s);
         return m.matches();
    }
 
四、相关应用:
    匹配中文字符的正则表达式: [\u4e00-\u9fa5]
    匹配双字节字符(包括汉字在内):[^\x00-\xff]
 
    应用:JS中计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)
    String.prototype.len=function(){return this.replace([^\x00-\xff]/g,"aa").length;}
 
    匹配空行的正则表达式:\n[\s| ]*\r
    匹配HTML标记的正则表达式:/<(.*)>.*<\/\1>|<(.*) \/>/
    匹配首尾空格的正则表达式:(^\s*)|(\s*$)
 
五、利用正则表达式限制网页表单里的文本框输入内容:注意单引号和双引号的嵌套,括号内是单引号
    只能输入中文:
    onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')"
    只能输入全角字符:
    onkeyup="value=value.replace(/[^\uFF00-\uFFFF]/g,'')"
    只能输入数字:
    onkeyup="value=value.replace(/[^\d]/g,'')"
    只能输入数字和中文:
    onkeyup="value=value.replace(/[\W]/g,'')
 
六、正则表达式在java中的相关应用:
 
    /**
  * 得到文件所在的磁盘目录
  * @param file
  * @return
  */
 public static String getFileDirectory(String file){
  String regEx = "{1,4}:.*[\\\\/]";
  String dir = "";
        Pattern p=Pattern.compile(regEx);
  Matcher m=p.matcher(file);
  if(m.find()){
   dir = m.group(m.groupCount());
  }
  return  dir;
 }
 
 /**
  * 得到文件名
  * @param file
  * @return
  */
 public static String getFileName(String file){
  String regEx =".+[\\\\|/](.+)$";
  String fileName = "";
        Pattern p=Pattern.compile(regEx);
  Matcher m=p.matcher(file);
  if(m.find()){
   fileName = m.group(m.groupCount());
  }
  return  fileName;
 }
 
 /**
  * 得到文件扩展名
  * @param file
  * @return
  */
 public static String getFileExtName(String file){
  String regEx = ".*\\.";
  Pattern p = Pattern.compile(regEx);
  Matcher m = p.matcher(file);
  String extName = m.replaceAll("");
  return extName;
 }
 
 /**
  * 得到html标签的属性
  * @param html 文件内容
  * @param label 要提取属性的标签名称,如:font ,img...
  */
 public static void getHtmlAttribute(String html,String label){
  Map<String,String> mapAttrib = new HashMap<String,String>();
  String regEx = "<"+label+"\\s*([^>]*)\\s *>";
  String regEx2 = "(+)\\s*=\\s*\"([^\"]+)\"";
  Pattern p = Pattern.compile(regEx);
  Matcher m = p.matcher(html);
  if(m.find()){
   String attribs = m.group(1);
   p = Pattern.compile(regEx2);
   m = p.matcher(attribs);
   while(m.find()){
    mapAttrib.put(m.group(1), m.group(2));
   }
  }
  printMapData(mapAttrib);
 }
 
 public static void printMapData(Map map){
  Set     entries   =   map.entrySet();
  Iterator   iter   =   entries.iterator();
  while(iter.hasNext())
  {
         Map.Entry   entry   =   (Map.Entry)iter.next();
       System.out.println(entry.getKey()+"="+entry.getValue());
  }
 }
 
 /**
  * 使用Jacob工具包完成word到html的转换
  * @param absPath 文件绝对路径
  */
 public static boolean wordFormatToHtml(String absPath) throws ProgramException{
     String FileFormat = "";
     FileFormat = getFileExtName(absPath);//文件类型
     if(FileFormat.equalsIgnoreCase("doc"))
     {
         String DocFile = absPath;
         //word文件的完整路径
         String HtmlFile = DocFile.substring(0, (DocFile.length() - 4)) + ".htm";
         //html文件的完整路径
         ActiveXComponent app = new ActiveXComponent("Word.Application");
         //启动word
         try{
           app.setProperty("Visible", new Variant(false));
           //设置word程序非可视化运行
           Dispatch docs = app.getProperty("Documents").toDispatch();
           Dispatch doc = Dispatch.invoke(docs,"Open", Dispatch.Method, new Object[]{DocFile,new Variant(false), new Variant(true)}, new int).toDispatch();
           //打开word文件
           Dispatch oWordBasic = (Dispatch) Dispatch.call(app, "WordBasic").getDispatch();
          
           Dispatch.call(oWordBasic, "AcceptAllChangesInDoc");
          
           Dispatch.invoke(doc,"SaveAs",Dispatch.Method, new Object[]{HtmlFile,new Variant(8)}, new int);
           //作为htm格式保存文件
           Dispatch.call(doc, "Close",new Variant(false));
           //关闭文件
         }
         catch (Exception e)
         {
    throw new ProgramException("error$Word转换为HTML时出错!");
         }
         finally
         {
           app.invoke("Quit", new Variant[] {});
           //退出word程序
         }
         //转化完毕
         return true;
     }
     return false;
   }
 
 /**
  * 逐行读取HTML文件内容
  * @param filePath  HTML文件的路径
  * @return
  * @throws ProgramException
  */
 public static String getHTMLContent(String filePath) throws ProgramException{
  StringBuffer sb=new StringBuffer();
  try{
  String line="";
  File file=new File(filePath);
  InputStreamReader read = new InputStreamReader (new FileInputStream(file));
  BufferedReader br=new BufferedReader(read);
  while((line=br.readLine())!=null){
   sb.append(line);
   sb.append('\n');//注意换行符写入
  }
  }catch(FileNotFoundException e){
   throw new ProgramException("error$读HTML文件时,文件没有找到");
  }catch(IOException e){
   throw new ProgramException("error$读HTML文件时,出现IO异常");
  }
  String temp=sb.toString();
  //不管图片
  String regEx = "<img\\s*([^>]*)\\s*>";
  Pattern p = Pattern.compile(regEx);
  Matcher m = p.matcher(temp);
  temp=m.replaceAll("");
  String regEx2 = "<v:imagedata\\s*([^>]*)\\s*>";
  Pattern p2 = Pattern.compile(regEx2);
  Matcher m2 = p2.matcher(temp);
  temp=m2.replaceAll("");
  
  temp = temp.replace("\'", "\"");
  return temp;
 }
页: [1]
查看完整版本: 正则表达式速成