正则表达式

来源:互联网 发布:mac安装flash插件 密码 编辑:程序博客网 时间:2024/06/05 03:22

通过static Pattern.complie(String regex)方法来编译正则表达式,它会根据传入的String类型的正则表达式生成一个Pattern对象,然后将想要检索的字符串传入Pattern对象的matcher()方法,生成一个Matcher对象,通过该Matcher对象的一些方法对字符串进行处理:

boolean matches()  判断整个字符串是否都匹配boolean lookingAt()    看字符串的起始部分是否匹配boolean find()       查找能够匹配的部分boolean find(int i)  从i位置开始查找String  group()    匹配的部分void reset()     将现有的Matcher对象用于新的字符串

这里有几点需要注意的是:
1.当使用lookingAt()后,如果开头部分可以匹配,则该部分不会再次匹配

public class Regex_Demo1 {    public static void main(String[] args) {        String regex = "\\d+";        String s = "12ksdf34lds56sl";        Matcher m = Pattern.compile(regex).matcher(s);        System.out.println(m.lookingAt()); // 使用lookingAt()方法        while(m.find()){            System.out.println(m.group());        }    }}

输出结果为:

true3456

可以看到,因为lookingAt()匹配了开头的‘12’,后面的find()就开始从‘12’后面的位置开始匹配。

2.当使用find(int i)时,Java的正则引擎不会自己传动,而是从位置i开始匹配,如果使用不带参数的find()方法,Java的正则引擎就会自己传动,每次都从上一次匹配成功的位置开始匹配。

public class Regex_Demo1 {    public static void main(String[] args) {        String regex = "\\d+";        String s = "12abksdf34lds56sl";        Matcher m = Pattern.compile(regex).matcher(s);        int i = 0;        while(m.find(i)){            System.out.println(m.group());            i++;        }    }}

结果:

122343434343434344565656566

3.关于group(int i)方法,如果不写参数,默认是第0组,即整个正则表达式匹配的部分,第一组就是正则表达式中第一个括号匹配的部分,依次类推:

public class Regex_Demo1 {    public static void main(String[] args) {        String regex = "(\\d+)[a-z]";        String s = "12bksdf34lds56sl";        Matcher m = Pattern.compile(regex).matcher(s);        while(m.find()){            System.out.println("第0组: " + m.group());            System.out.println("第1组: " + m.group(1));        }    }}

结果:

0组: 12b第1组: 120组: 34l1组: 340组: 56s第1组: 56

用于扫描输入

默认情况写,Scanner根据空白符对输入进行分词,但也可以用正则表达式指定定界符

public class Regex_Demo2 {    public static void main(String[] args) {        Scanner sc = new Scanner("12 , 34  , 56,78");        sc.useDelimiter("\\s*,\\s*");        while(sc.hasNextInt()){            System.out.println(sc.nextInt());        }    }}

输出:

12345678

当然,也可以一次读取一行然后又split()方法进行分词。

原创粉丝点击