第十三章:字符串(下)

13.6 正则表达式 [regular expression] (regex)

用于专门操作字符串。操作字符串的规则。
在正则表达式中,括号有这表达式分组的效果。竖直线 | 表示 或操作。
正则表达式语法:http://blog.csdn.net/u014115673/article/details/53816455

具体操作功能
  1. 匹配:String类中的matches(String regex):用规则匹配整个字符串,只要有一处不符合规则就匹配结束,返回false
  2. 切割:String类中的split(String regex)
    如果你想对正则的结果进行重用,用括号把正则表达式括起来,叫做组.从1开始编号.通过使用\来使用组的内容,比如想使用第一组的内容:(.)\1
  3. 替换:replaceAll(String regex, String replacement)
    replaceFirst(String regex, String replacement)
  4. 获取:取出符合规则的内容

    // 匹配连续3个字母
        // 将规则封装成对象
        Pattern p = Pattern.compile("\\b[a-z]{3}\\b");
        // 正则对象和要作用的字符串相关联,获取匹配器对象
        String str = "ming tian jiu yao fang jia la,da jia";
        Matcher ma = p.matcher(str);
        // 匹配,会导致匹配索引向下移,那么在find() 的时候,就不是在文本头查找了。就这个例子而言,ma.matches()调用,开始匹配匹配到g的时候不符合规则,所以打印结果是false,此时指针指到了g处。
        System.out.println(ma.matches()); 
        // 查找
        while (ma.find()) {
            // 获得匹配的字符串
            System.out.println(ma.group());
            System.out.println(ma.start() + "..." + ma.end());
        }
    
13.6.4 Pattern 和 Matcher

导入com.util.regex包,然后用 static Pattern.compile(“正则字符串”)方法来编译你的正则表达式。他会根据你的String类型的正则表达式生成一个Pattern对象。接下来把你想要检索的字符串传入Pattern对象的matcher()方法。matcher()方法会生成一个Matcher对象。接下来你就可以使用Matcher对象的方法操作了。

Pattern类中的静态方法:
static boolean matches(String regex, CharSequence input):该方法用以检查regex是否匹配整个CharSequence类型的input参数。
Matcher类上的方法:
boolean matches():判断正则表达式和整个字符串是否匹配
boolean lookingAt():判断该字符串的(不必是整个字符串)始部分是否能够匹配该模式。

组(Groups)
组的操作

Pattern标记

Pattern标记
Pattern标记

Pattern.MULTILINE 、Pattern.CASE_INSENSITIVE、 Pattern.COMMENTS(对声明或文档有用),这三个标记很有用。
Pattern.DOTALL :在这种模式下,表达式’.’可以匹配任意字符,包括表示一行的结束符。默认情况下,表达式’.’不匹配行的结束符。

13.6.5 split()

public String[] split(CharSequence input)
public String[] split(CharSequence input, int limit): 可以限制分割成的字符串的数量(limit个)。

13.6.6 替换操作

替换操作

    public class TheReplacements {

    /*! Here's a block of text to use as input to
    the regular expression matcher. Note that we'll
    first extract the block of text by looking for
    the special delimiters, then process the
    extracted block. !*/

    public static void main(String[] args) throws Exception {
        String s = TextFile.read("TheReplacements.java");
        System.out.println(s);
        // Match the specially commented block of text above:
        Matcher mInput =
                Pattern.compile("/\\*!(.*)!\\*/", Pattern.DOTALL)
                        .matcher(s);
        if (mInput.find())
            s = mInput.group(1); // Captured by parentheses
        // Replace two or more spaces with a single space:
        s = s.replaceAll(" {2,}", " ");
        // Replace one or more spaces at the beginning of each
        // line with no spaces. Must enable MULTILINE mode:
        s = s.replaceAll("(?m)^ +", "");
        System.out.println(s);
        s = s.replaceFirst("[aeiou]", "(VOWEL1)");

        StringBuffer sbuf = new StringBuffer();
        Pattern p = Pattern.compile("[aeiou]");
        Matcher m = p.matcher(s);
        // Process the find information as you perform the replacements:
        while (m.find())
            m.appendReplacement(sbuf, m.group().toUpperCase());
        // Put in the remainder of the text:
        m.appendTail(sbuf);
        System.out.println(sbuf);
    }
}

代码解释

13.6.7 reset()

通过reset()方法可以将现有的Matcher对象应用于一个新的字符序列。

public class Resetting {
    public static void main(String[] args) throws Exception {
        Matcher m = Pattern.compile("[frb][aiu][gx]")
                .matcher("fix the rug with bags");
        while (m.find())
            System.out.print(m.group() + " ");
        System.out.println();
        m.reset("fix the rig with rags");
        while (m.find())
            System.out.print(m.group() + " ");
    }
}

使用不带参数的reset()方法,可以将Matcher对象重新设置到当前字符序列的起始位置。

13.7.2 用正则表达式扫描输入
public class ThreatAnalyzer {
    static String threatData =
            "58.27.82.161@02/10/2005\n" +
            "204.45.234.40@02/11/2005\n" +
            "58.27.82.161@02/11/2005\n" +
            "58.27.82.161@02/12/2005\n" +
            "58.27.82.161@02/12/2005\n" +
            "[Next log section with different data format]";

    public static void main(String[] args) {
        Scanner scanner = new Scanner(threatData);
        String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@" +
                "(\\d{2}/\\d{2}/\\d{4})";
        while (scanner.hasNext(pattern)) {
            scanner.next(pattern);
            // 获取匹配到的结果
            MatchResult match = scanner.match();
            String ip = match.group(1);
            String date = match.group(2);
            System.out.format("Threat on %s from %s\n", date, ip);
        }
    }
}

13.8 StringTokenizer

在正式引入正则表达式(J2SE1.4)和Scanner类(Java SE5)之前,分割字符串的唯一方法是使用StringTokenizer。

public class ReplacingStringTokenizer {
    public static void main(String[] args) {
        String input = "But I'm not dead yet! I feel happy!";
        StringTokenizer stoke = new StringTokenizer(input);
        while (stoke.hasMoreElements())
            System.out.print(stoke.nextToken() + " ");

        System.out.println();

        System.out.println(Arrays.toString(input.split(" ")));

        Scanner scanner = new Scanner(input);
        while (scanner.hasNext())
            System.out.print(scanner.next() + " ");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

outer199

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值