正则表达式知识详解之匹配开头或结尾 (java版示例)

正则表达式知识详解系列,通过代码示例来说明正则表达式知识
源代码下载地址:http://download.csdn.net/detail/gnail_oug/9504094

示例功能:
1、匹配字符串的开头
2、匹配字符串的结尾

package com.songguoliang.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则表达式知识
 * @date 2016-04-15 10:14:48
 * @author sgl
 */
public class Demo01 {

    /**
     * 匹配字符串,并且是以该字符串开头或结尾
     * 字符串边界的元字符有两个:一个是用来匹配字符串开头的^,另一个是用来匹配字符串结尾的$
     * @date 2016-04-20 15:19:14
     * @author sgl
     */
    public static void stringBoundary(){
        String str="hello world,hello java,hello java";

        System.out.println("===========匹配字符串===========");
        //匹配str中所有字符串hello,这时str中3个hello都能匹配上,通过下面打印的匹配上的字符串的位置可以看出
        Pattern p=Pattern.compile("hello");
        Matcher m=p.matcher(str);
        while(m.find()){
            System.out.println(m.group()+"   位置:["+m.start()+","+m.end()+"]");
        }
        System.out.println("===========匹配字符串,并且该字符串是在开头的位置===========");
        // ^表示匹配字符串的开头,但是如何在[]里面则表示非,如[^a-f] 不匹配a-f
        // "hello""^hello"的区别就是:前者匹配时不管是不是在开头位置,只要能匹配就行,后者则是不但要能匹配而且还要是在开头的位置。这时str中3个hello只有第1个能匹配上。
        p=Pattern.compile("^hello");
        m=p.matcher(str);
        while(m.find()){
            System.out.println(m.group()+"   位置:["+m.start()+","+m.end()+"]");
        }

        System.out.println("===========匹配字符串===========");
        //这时str中两个java都能匹配上
        p=Pattern.compile("java");
        m=p.matcher(str);
        while(m.find()){
            System.out.println(m.group()+"   位置:["+m.start()+","+m.end()+"]");
        }
        System.out.println("===========匹配字符串,并且是该字符串是在末尾的位置===========");
        //这时str中两个java只有第2个才能匹配上
        p=Pattern.compile("java$");
        m=p.matcher(str);
        while(m.find()){
            System.out.println(m.group()+"   位置:["+m.start()+","+m.end()+"]");
        }
    }


    public static void main(String[] args) {
        Demo01.stringBoundary();

    }
}

运行结果:

===========匹配字符串===========
hello   位置:[0,5]
hello   位置:[12,17]
hello   位置:[23,28]
===========匹配字符串,并且该字符串是在开头的位置===========
hello   位置:[0,5]
===========匹配字符串===========
java   位置:[18,22]
java   位置:[29,33]
===========匹配字符串,并且是该字符串是在末尾的位置===========
java   位置:[29,33]

最新代码可参看https://github.com/songguoliang/Demo4Regex

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值