分享

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

 三十的狼 2018-01-19

正则表达式知识详解系列,通过代码示例来说明正则表达式知识
源代码下载地址: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();

    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

运行结果:

===========匹配字符串===========
hello   位置:[0,5]
hello   位置:[12,17]
hello   位置:[23,28]
===========匹配字符串,并且该字符串是在开头的位置===========
hello   位置:[0,5]
===========匹配字符串===========
java   位置:[18,22]
java   位置:[29,33]
===========匹配字符串,并且是该字符串是在末尾的位置===========
java   位置:[29,33]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多