正则表达式

知识点

*掌握正则表达式的作用

*掌握正则表达式的匹配模式

*掌握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.lengthi++) {

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());

}

}

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值