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;
}
}
常用的正则表达式
最新推荐文章于 2024-10-25 09:10:58 发布
本文介绍了一种使用Java正则表达式的方法来验证QQ号码的有效性。详细解释了正则表达式的各个组成部分,如字符类、预定义字符和贪婪数量词,并通过实例演示如何确保QQ号码符合特定的格式要求:长度为5-15位,不能以0开头,且必须全为数字。
2093

被折叠的 条评论
为什么被折叠?



