正则表达式的定义:描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。
直接代码(代码里面有对应的注解):
public class regularExpression {
public static void main(String[] args) {
//单个字符
String re = "[a]";
String a = "a";
String c = "aa";
System.out.println(c.matches(re));
System.out.println(a.matches(re));
System.out.println("++++++++++++++++++++++++++++++++++++");
/**
* 范围字符限定
* 【a-z】:表示小写字母的范围;
* 【A-Z】:表示大写字母的范围
* 【0-9】:表示数字的范围
* 【a-zA-Z】:表示可以取大小写字母的范围。
* 【a-z0-9A-Z】:表示可以取大小写字母或者数字的范围的范围。
*/
String rex = "[a-z]";
String rex1 = "[a-z0-9]";
String rex2 = "[a-zA-Z]";
String ab = "a";
String cb = "1";
String db = "Z";
System.out.println(ab.matches(rex));
System.out.println(cb.matches(rex1));
System.out.println(db.matches(rex2));
System.out.println("++++++++++++++++++++++++++++++++++++");
//取反限定【^】:表示内容不能为所以用的
String rex3 = "[^ad]";
String t = "a";
String n = "1";
System.out.println(t.matches(rex3));
System.out.println(n.matches(rex3));
System.out.println("++++++++++++++++++++++++++++++++++++");
/**
* 长度限定
* 【a-z】{1}:表示只能有一个小写字母的范围;
* 【a-z】{5}:表示内容为小写字母且长度必须是五;
* 【0-9】{3,8}:表示内容为数字且长度为3,8之间;
* 【0-9】{3,}:表示内容为数字且长度最小值为3;
* 【0-9】{0,8}:表示内容为数字且长度为0,8之间;
*/
String rexg = "[a-z]{1}";
String rexh = "[a-z]{3,8}";
String rexj = "[a-z]{5}";
String rexk = "[a-z]{3,}";
String rexl = "[a-z]{0,3}";
String g = "r";
String h = "rqwertyui";//这个字符串的长度为9,所以会报错
String j = "rjklj";
String k = "rsdagfgrasad";
String l = "";//这个可以看作长度为零
System.out.println(g.matches(rexg));
System.out.println(h.matches(rexh));
System.out.println(j.matches(rexj));
System.out.println(k.matches(rexk));
System.out.println(l.matches(rexl));
System.out.println("++++++++++++++++++++++++++++++++++++");
/**
* 长度限定符号
* 【a-z】?== 【a-z】{0,1}:表示零次或一次;
* 【a-z】+ == 【a-z】{1,}:表示一次或多次;
* 【0-9】* == 【0-9】{0,}:表示零次或多次;
*/
String rexg1 = "[a]?";//这里是只能有零个或者一个a;
String rexh1 = "[a-z]+";
String rexj1 = "[a]*";
String g1 = "aa";//a有两个了
String h1 = "rqwertyui";//这个字符串的长度为9
String j1= "rjklj";
System.out.println(g1.matches(rexg1));
System.out.println(h1.matches(rexh1));
System.out.println(j1.matches(rexj1));
}
}
PS:注解界面的【】是中文输入法下的表示.
代码的运行结果截图如下;
还找了一些预定义和比较常见的正则表达式的截图:
预定义字符:
比较常见的正则表达式:
以上呢就是我个人学习时候的一些理解,如果有错误的地方,还望指正。