常用的正则表达式

本文介绍了一种使用Java正则表达式的方法来验证QQ号码的有效性。详细解释了正则表达式的各个组成部分,如字符类、预定义字符和贪婪数量词,并通过实例演示如何确保QQ号码符合特定的格式要求:长度为5-15位,不能以0开头,且必须全为数字。

package MatchesDemo;
/***
 * boolean matches(String regex) 判断当前字符是否匹配指定的正则表达式,匹配返回true,失败返回false;
 * A 字符
 * x 字符x      \\ 反斜线字符
 *
 * B 字符类
 * [abc]`a或者b或者c (简单类)
 * [^abc]  任何字符 除了 a,b,c(否定)
 * [a-zA-z] a到z或A-Z两头的字符包括在内(范围)
 *
 * C 预定义的字符
 * . 任何字符(与行结束符肯匹配也可能不匹配)
 * \d  数字[0-9]
 * \D 非数字[^0-9]
 * \s 空白字符[\t\n\x0B\f\r]
 * \S 非空白字符[^\s]
 * \w 单词字符[a-zA-Z_0-9]
 * \w 非单词字符[^\w]
 *
 * D Greedy 数量词
 * X?  X, 一次或一次也没有
 * X*  X,零次或多次
 * X+ X,一次或多次
 * X{n}  X,恰好n次
 * X{n,} X,至少n次
 * X{n,m} X,至少n次但是不超过m次
 * */
public class NatchesDemo {
    /** 检验qq号码
     *  长度为5-15
     *  不能以0开始
     *  必须全是数字
     * */
    public static void main(String[] args) {
        String s="1111345";
        String s1="1111345111134511113451111345";
        String s2="111";
        String s3="11a1345";
        String s4="01111345";
//        System.out.println(method(s));
//        System.out.println(method(s1));
//        System.out.println(method(s2));
//        System.out.println(method(s3));
//        System.out.println(method(s4));


        boolean matches = s.matches("[1-9][0-9]{4,14}");
        boolean matches1 = s1.matches("[1-9][0-9]{4,14}");
        boolean matches2 = s2.matches("[1-9][0-9]{4,14}");
        boolean matches3 = s3.matches("[1-9][0-9]{4,14}");
        boolean matches4 = s4.matches("[1-9][0-9]{4,14}");
        System.out.println(matches);
        System.out.println(matches1);
        System.out.println(matches2);
        System.out.println(matches3);
        System.out.println(matches4);


    }
    public static boolean method(String s){
        int length=s.length();
        if (length<5||length>15){
            return false;
        }
        if (s.startsWith("0")){
            return false;
        }
        for (int i = 0; i < s.length(); i++) {
            char chs=s.charAt(i);
            if (chs<'0'||chs>'9'){
                return false;
            }
        }
        return true;

    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值