知识点
*掌握正则表达式的作用
*掌握正则表达式的匹配模式
*掌握Pattern类和Matcher类的作用
*掌握String对正则的支持
具体用途
正则表达式可以方便的对数据进行匹配,可以执行非常复杂的字符串拆分、检验、替换。
正则表达式怎么写? 怎么使用正则表达式?
使用正则表达式的区别:
例子:
public class RegexDemo01 { public static void main(String[] args) { String str = "12a456789"; char[] a = str.toCharArray(); boolean b = true; for (int i = 0; i < a.length; i++) { if(a[i]<'0'||a[i]>'9'){ b = false; break; } } if(b){ System.out.println("是数字组成"); }else{ System.out.println("不是数字组成"); } } }
public class RegexDemo02 { public static void main(String[] args) { String str = "123456789"; if(Pattern.compile("[0-9]+").matcher(str).matches()){ System.out.println("是数字组成"); }else{ System.out.println("不是数字组成"); } } } |
Pattern类和 Matcher类
public class RegexDemo03 { public static void main(String[] args) { String str = "1993-03-23";//日期格式 String pat = "\\d{4}-\\d{2}-\\d{2}"; Pattern p = Pattern.compile(pat);//实例化Pattern类 Matcher m = p.matcher(str);//进行验证的匹配,使用正则 if(m.matches()){ System.out.println("是日期格式"); }else{ System.out.println("不是日期格式"); } } }
|
规范 | 描述 | 规范 | 描述 |
\\ | 反斜杠 | \t | 制表符 |
\n | 换行 | [abc] | 字符a、b或c |
[^abc] | 除abc之外的任意 | [a-zA-Z0-9] | 数字、字母组成 |
\d | 数字 | \D | 非数字 |
\w | 字母数字下划线 | \W | 非字母数字下划线 |
\s | 任意的空白符 | \S | 非空白符 |
^ | 开始 | $ | 结尾 |
. | 除换行符之外 |
|
|
数量表示(X表示一组规范) | |||
X | 必须出现一次 | X? | 可以出现0、1次 |
X* | 任意次数 | X+ | 至少出现一次 |
X{n} | 出现n次 | X{n,} | 必须出现n次以上 |
X{n,m} | 必须出现在n-m次中间 |
|
|
逻辑运算符 | |||
XY | 两个规范 | X|Y | X规范或者Y |
|
|
|
|
实例:
public class RegexDemo03 { public static void main(String[] args) { // 正则匹配 String str = "1993-03-23";// 日期格式 String pat = "\\d{4}-\\d{2}-\\d{2}"; Pattern p = Pattern.compile(pat);// 实例化Pattern类 Matcher m = p.matcher(str);// 进行验证的匹配,使用正则 if (m.matches()) {// 匹配 System.out.println("是日期格式"); } else { System.out.println("不是日期格式"); }
// 正则拆分 String str1 = "A123B232D3434C666666E222F";// 按照数字进行拆分 String pat1 = "\\d+"; Pattern p1 = Pattern.compile(pat1);// 实例化Pattern类 String[] s = p1.split(str1); for (String ss : s) { System.out.print(ss + "\t"); }
// 正则替换 String str2 = "A123B232D3434C666666E222F";// 按照数字进行拆分 String pat2 = "\\d+"; Pattern p2 = Pattern.compile(pat2);// 实例化Pattern类 Matcher m1 = p2.matcher(str2); String newstr = m1.replaceAll("_"); System.out.println(newstr); // 正则find String str3 = "A123B232D3434C666666E222F";// 按照数字进行拆分 String pat3 = "\\d+"; Pattern p3 = Pattern.compile(pat3);// 实例化Pattern类 Matcher m2 = p3.matcher(str3); //boolean b = m2.find(); while(m2.find()){ //System.out.println(m2.start()); System.out.println(m2.group()); } } }
|