从制造到创造
软件工程师成长之路
posts - 292,  comments - 96,  trackbacks - 0
在String类中,有四个特殊的方法:


public String[] split(String regex)
根据给定的正则表达式的匹配来拆分此字符串。

该方法的作用就像是使用给定的表达式和限制参数 0 来调用两参数 split 方法。因此,结果数组中不包括结尾空字符串。

例如,字符串 "boo:and:foo" 产生带有下面这些表达式的结果:

Regex 结果
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }
参数: regex - 定界正则表达式
返回: 字符串数组,根据给定正则表达式的匹配来拆分此字符串,从而生成此数组。
抛出: PatternSyntaxException - 如果正则表达式的语法无效

public String[] split(String regex, int limit)
根据匹配给定的正则表达式来拆分此字符串。

此方法返回的数组包含此字符串的每个子字符串,这些子字符串由另一个匹配给定的表达式的子字符串终止或由字符串结束来终止。数组中的子字符串按它们在此字符串中的顺序排列。如果表达式不匹配输入的任何部分,则结果数组只具有一个元素,即此字符串。

limit 参数控制模式应用的次数,因此影响结果数组的长度。如果该限制 n 大于 0,则模式将被最多应用 n - 1 次,数组的长度将不会大于 n,而且数组的最后项将包含超出最后匹配的定界符的所有输入。如果 n 为非正,则模式将被应用尽可能多的次数,而且数组可以是任意长度。如果 n 为零,则模式将被应用尽可能多的次数,数组可有任何长度,并且结尾空字符串将被丢弃。

例如,字符串 "boo:and:foo" 使用这些参数可生成下列结果:

Regex Limit 结果
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }

这种形式的方法调用 str.split(regex, n) 产生与以下表达式完全相同的结果:

Pattern.compile(regex).split(str, n)

参数: regex - 定界正则表达式 ;limit - 结果阈值,如上所述

返回: 字符串数组,根据给定正则表达式的匹配来拆分此字符串,从而生成此数组

public String replaceAll(String regex, String replacement)
使用给定的 replacement 字符串替换此字符串匹配给定的正则表达式的每个子字符串。

此方法调用的 str.replaceAll(regex, repl) 形式产生与以下表达式完全相同的结果:

Pattern.compile(regex).matcher(str).replaceAll(repl)

参数: regex - 用来匹配此字符串的正则表达式

返回: 得到的 String

public String replaceFirst(String regex, String replacement)
使用给定的 replacement 字符串替换此字符串匹配给定的正则表达式的第一个子字符串。

此方法调用的 str.replaceFirst(regex, repl) 形式产生与以下表达式完全相同的结果:

Pattern.compile(regex).matcher(str).replaceFirst(repl)

参数:regex - 用来匹配此字符串的正则表达式

返回: 得到的 String

这四个方法中都有一个参数为正则表达式(Regular Expression),而不是普通的字符串。

在正则表达式中具有特殊含义的字符

特殊字符

描述

    .     表示任意一个字符
    [abc]     表示a、b或c中的任意一个字符
    [^abc]     除a、b和c以外的任意一个字符
    [a-zA-z]     介于a到z,或A到Z中的任意一个字符
    \s     空白符(空格、tab、换行、换页、回车)
    \S     非空白符
    \d     任意一个数字[0-9]
    \D     任意一个非数字[^0-9]
    \w     词字符[a-zA-Z_0-9]
    \W     非词字符

表示字符出现次数的符号

表示次数的符号

描述

    *     0 次或者多次
    +     1 次或者多次
    ?     0 次或者 1 次
    {n}     恰好 n 次
    {n, m}     至少 n 次,不多于 m 次


public class RegDemo2 {

    
/**
     * 
@param args
     
*/
    
public static void main(String[] args) {
        
// 例如,字符串 "boo:and:foo" 产生带有下面这些表达式的结果: Regex 结果
        
// : { "boo", "and", "foo" }
        
// o { "b", "", ":and:f" }
        String tempStr = "boo:and:foo";
        String[] a 
= tempStr.split(":");        
        pringStringArray(a);
        
        String[] b 
= tempStr.split("o");
        pringStringArray(b);
        
        System.out.println(
"--------------------------");
        
        
// Regex Limit 结果
        
// : 2 { "boo", "and:foo" }
        
// : 5 { "boo", "and", "foo" }
        
// : -2 { "boo", "and", "foo" }
        
// o 5 { "b", "", ":and:f", "", "" }
        
// o -2 { "b", "", ":and:f", "", "" }
        
// o 0 { "b", "", ":and:f" }
        pringStringArray(tempStr.split(":"2));
        pringStringArray(tempStr.split(
":"5));
        pringStringArray(tempStr.split(
":"-2));
        pringStringArray(tempStr.split(
"o"5));
        pringStringArray(tempStr.split(
"o"-2));
        pringStringArray(tempStr.split(
"o"0));

        
// 字符串 "boo:and:foo"中的所有“:”都被替换为“XX”,输出:booXXandXXfoo
        System.out.println(tempStr.replaceAll(":""XX"));
        
        
// 字符串 "boo:and:foo"中的第一个“:”都被替换为“XX”,输出: booXXand:foo
        System.out.println(tempStr.replaceFirst(":""XX"));
    }

    
public static void pringStringArray(String[] s) {
        
int index = s.length;
        
for (int i = 0; i < index; i++) {
            System.err.println(i 
+ "" + s[i]);
        }
    }
}

下面的程序演示了正则表达式的用法:
/**
 * discription:
 * 
 * 
@author CoderDream
 * 
 
*/
public class RegularExTester {

    
/**
     * 
@param args
     
*/
    
public static void main(String[] args) {
        
// 把字符串中的“aaa”全部替換為“z”,打印:zbzcz
        System.out.println("aaabaaacaaa".replaceAll("a{3}""z"));

        
// 把字符串中的“aaa”、“aa”或者“a”全部替換為“*”,打印:*b*c*
        System.out.println("aaabaaca".replaceAll("a{1,3}""\\*"));

        
// 把字符串中的數字全部替換為“z”,打印:zzzazzbzzcc
        System.out.println("123a44b35cc".replaceAll("\\d""z"));

        
// 把字符串中的非數字全部替換為“0”,打印:1234000435000
        System.out.println("1234abc435def".replaceAll("\\D""0"));

        
// 把字符串中的“.”全部替換為“\”,打印:com\abc\dollapp\Doll
        System.out.println("com.abc.dollapp.Doll".replaceAll("\\.""\\\\"));

        
// 把字符串中的“a.b”全部替換為“_”,
        
// “a.b”表示長度為3的字符串,以“a”開頭,以“b”結尾
        
// 打印:-hello-all
        System.out.println("azbhelloahball".replaceAll("a.b""-"));

        
// 把字符串中的所有詞字符替換為“#”
        
// 正則表達式“[a-zA-z_0-9]”等價于“\w”
        
// 打印:#.#.#.#.#.#
        System.out.println("a.b.c.1.2.3.4".replaceAll("[a-zA-z_0-9]""#"));
        System.out.println(
"a.b.c.1.2.3.4".replaceAll("\\w""#"));
    }
}

值得注意的是,由于“.”、“?”和“*”等在正则表达式中具有特殊的含义,如果要表示字面上的这些字符,必须以“\\”开头。例如为了把字符串“com.abc.dollapp.Doll”中的“.”替换为“\”,应该调用replaceAll("\\.",\\\\)方法。

Java中的正则表达式类


 public interface MatchResult


    

匹配操作的结果。

此接口包含用于确定与正则表达式匹配结果的查询方法。通过 MatchResult 可以查看匹配边界、组和组边界,但是不能修改


 public final class Matcher

extends Object
implements MatchResult

    

通过解释 Pattern字符序列 执行匹配操作的引擎。

通过调用模式的 matcher 方法从模式创建匹配器。创建匹配器后,可以使用它执行三种不同的匹配操作:

  • matches 方法尝试将整个输入序列与该模式匹配。

  • lookingAt 尝试将输入序列从头开始与该模式匹配。

  • find 方法扫描输入序列以查找与该模式匹配的下一个子序列。

每个方法都返回一个表示成功或失败的布尔值。通过查询匹配器的状态可以获取关于成功匹配的更多信息。


 public final class Pattern

extends Object
implements Serializable

    

正则表达式的编译表示形式。

指定为字符串的正则表达式必须首先被编译为此类的实例。然后,可将得到的模式用于创建 Matcher 对象,依照正则表达式,该对象可以与任意字符序列匹配。执行匹配所涉及的所有状态都驻留在匹配器中,所以多个匹配器可以共享同一模式。

因此,典型的调用顺序是

 Pattern p = Pattern.compile("a*b");
    Matcher m = p.matcher("aaaaab");
    boolean b = m.matches();

在仅使用一次正则表达式时,可以方便地通过此类定义 matches 方法。此方法编译表达式并在单个调用中将输入序列与其匹配。语句

 boolean b = Pattern.matches("a*b", "aaaaab");

等效于上面的三个语句,尽管对于重复的匹配而言它效率不高,因为它不允许重用已编译的模式。

此类的实例是不可变的,可供多个并发线程安全使用。Matcher 类的实例用于此目的则不安全。


测试代码:

/**
 * discription:Java中正则表达式类的使用
 * 
 * 
@author CoderDream
 * 
 
*/
public class RegDemo {

    
/**
     * 
@param args
     
*/
    
public static void main(String[] args) {
        
// 檢查字符串中是否含有“aaa”,有返回:true,無返回:false
        System.out.println(isHaveBeenSetting("a{3}""aaabaaacaaa"));
        System.out.println(isHaveBeenSetting(
"a{3}""aab"));
        
        
// 把字符串“abbaaacbaaaab”中的“aaa”全部替換為“z”,打印:abbzbza
        System.out.println(replaceStr("a{3}""abbaaabaaaa""z"));
    }

    
/**
     * 
     * 
@param regEx
     *            设定的正则表达式
     * 
@param tempStr
     *            系统参数中的设定的字符串
     * 
@return 是否系统参数中的设定的字符串含有设定的正则表达式 如果有的则返回true
     
*/
    
public static boolean isHaveBeenSetting(String regEx, String tempStr) {
        
boolean result = false;
        
try {
            Pattern p 
= Pattern.compile(regEx);
            Matcher m 
= p.matcher(tempStr);
            result 
= m.find();
        } 
catch (Exception e) {
            e.printStackTrace();
        }
        
return result;
    }

    
/**
     * 将字符串含有的regEx表达式替换为replaceRegEx
     * 
     * 
@param regEx
     *            需要被替换的正则表达式
     * 
@param tempStr
     *            替换的字符串
     * 
@param replaceRegEx
     *            替换的正则表达式
     * 
@return 替換好后的字符串
     
*/
    
public static String replaceStr(String regEx, String tempStr,
            String replaceRegEx) {
        Pattern p 
= Pattern.compile(regEx);
        Matcher m 
= p.matcher(tempStr);
        tempStr 
= m.replaceAll(replaceRegEx);

        
return tempStr;
    }
}
posted on 2008-02-28 11:40 CoderDream 阅读(2329) 评论(0)  编辑  收藏 所属分类: 学习笔记

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


网站导航:
 

<2008年2月>
272829303112
3456789
10111213141516
17181920212223
2425262728291
2345678

常用链接

留言簿(9)

我参与的团队

随笔分类(245)

随笔档案(239)

文章分类(3)

文章档案(3)

收藏夹(576)

友情链接

搜索

  •  

积分与排名

  • 积分 - 454027
  • 排名 - 115

最新评论

阅读排行榜

评论排行榜