一般的來說,使用正則表達式可以實現四個功能:匹配、分割、替換、刪除。
嚴格的來說,其實替換和刪除是一個功能,不過,從邏輯功能上來說,是不同的。
下面,就是一個簡單的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.tkk7.com/zhyiwww
|----------------------------------------------------------------------------------------|
posted on 2007-09-19 17:40
zhyiwww 閱讀(893)
評論(0) 編輯 收藏 所屬分類:
正則表達式