01.正则表达式

2016-11-29  本文已影响0人  celloist

pepper send 1 bottle of perfume to nulo,It's price is 200¥,and her number is 13344445555

正则表达式:
(1)\b 元字符: 表示单词的开头或结尾,也就是单词的分界处,通常英文的单词是由空格,标点符号或者换行来分隔的,但是\b并不匹配这些单词分隔字符中的任何一个,它只匹配一个位置。

\bnulo\b 得到 nulo

(2). 元字符:匹配除了换行符以外的任意字符
(3)* 元字符:代表的不是字符,也不是位置,而是数量——它指定*前边的内容可以连续重复使用任意次以使整个表达式得到匹配

.* 连用则能匹配 任意数量的不包含换行的字符


正则表达式验证6到10个字符串或数字的长度: ^[a-zA-Z0-9]{6,10}$


Java使用正则表达式:

public static void main(String[] args) {

        String str = "a little boy whose age is 5 years old and phone number is 133 5678 9562!";
        // 以下正则表达式表示匹配一个手机号码: \s 表示一个空格,\d表示数字,{3}表示前面的内容连续出现的次数
        String regix = "\\s\\d{3}\\s\\d{4}\\s\\d{4}";
        // Pattern类的对象p表示编译后的正则表达式,compile()方法内的参数为正则表达式的内容
        Pattern p = Pattern.compile(regix);
        // matcher()方法返回一个Matcher对象
        Matcher m = p.matcher(str);
        while (m.find()) {
            //group()方法返回与正则表达式匹配的内容
            System.out.println(m.group());
            //start()方法返回匹配的起始位置
            System.out.println(m.end()-1-m.start());
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读