zhyiwww
用平实的笔,记录编程路上的点点滴滴………
posts - 536,comments - 394,trackbacks - 0
一般的来说,使用正则表达式可以实现四个功能:匹配、分割、替换、删除。
严格的来说,其实替换和删除是一个功能,不过,从逻辑功能上来说,是不同的。
下面,就是一个简单的demo也实现了上面的几个功能,虽然比较简单,但是,对于不同的需求,都有对应的实现。
希望对初学的您也能提供一点思路。

package org.zy.demo;

import java.io.BufferedInputStream;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * a testing demo of regular express
 * @author zy
 *
 */
public class RegularExpDemo {

    public static void main(String[] args) {
        RegularExpDemo red = new RegularExpDemo();
        red.match();
        red.split();
        red.replace();
        red.delete();
    }

    /*
     * just test match @param parent @param son
     */
    public void match() {
        String parent = "abcdefdssdefdsfed";
        String son = "d(ef)";
        Pattern p = Pattern.compile(son);
        Matcher m = p.matcher(parent);

        while (m.find()) {
            System.out.println(" start  :  " + m.start());
            System.out.println(" end : " + m.end());
        }

    }

    /*
     * just test split
     */
    public void split() {
        String parent = "a/b/c/d/e/f/sd/ikshk/alke";
        String son = "/";
        Pattern p = Pattern.compile(son);

        String[] lstr = p.split(parent);
        int i = 0;
        while (i < lstr.length) {
            System.out.println(lstr[i]);
            i++;
        }

    }

    /*
     * test replace
     */
    public void replace() {

        String parent = "abcdefdssdefdsfed";
        String son = "d[e|s].";
        Pattern p = Pattern.compile(son);
        Matcher m = p.matcher(parent);

        String lStr = m.replaceAll("ccgg");
        System.out.println(parent);
        System.out.println(lStr);

    }

    /*
     * test delete
     */
    public void delete() {

        String parent = "abcdefdssdefdsfed";
        String son = "d[e|s].";
        Pattern p = Pattern.compile(son);
        Matcher m = p.matcher(parent);

        String lStr = m.replaceAll("");
        System.out.println(parent);
        System.out.println(lStr);

    }
}



|----------------------------------------------------------------------------------------|
                           版权声明  版权所有 @zhyiwww
            引用请注明来源 http://www.blogjava.net/zhyiwww   
|----------------------------------------------------------------------------------------|
posted on 2007-09-19 17:40 zhyiwww 阅读(876) 评论(0)  编辑  收藏 所属分类: 正则表达式

只有注册用户登录后才能发表评论。


网站导航: