java正则表达式用法6_轻松掌握java正则表达式使用

一、规则

正则表达式,按字面意思理解就是字符串匹配的规则表达式,匹配方式:从左向右匹配,如:定义一个字符串:String str = "abc";str.macthes("abc");// 返回true,意思是字符串str和规则表达式"abc"恰好能够匹配;str.macthes("cba");// 返回false,意思是字符串str和规则表达式"cba"不能匹配。至于规则表达式,可以按照如下规则进行组装:

字符

含义

java举例

^

开头

$

结尾

.

单个任意字符

*

前面任意个字符

?

0个或一个

+

至少一个字符

\d

匹配数字

“19\d\d”,匹配1900-1999

\D

匹配非数字

\w

字母数字下划线

\W

非字母数字下划线

\s

空格,tab,制表符

\S

非空格、tab制表符

\u+十六进制

配置非as码

“a\u548cc”,匹配a和c

“abc”

精确匹配

()

用于分组

[]

匹配范围

[^]

不包含这个范围

{n}

表示个数范围

{2,3}或{2,}或{2}

特殊字符

需要加\

|

或者

二、举例

分割字符串:String.split();

搜索字串:Matcher.find();

替换字符串:String.replaceAll();

1.字符串操作

精确匹配

public static void main(String[] args) {

String str="we are happy";

//精确匹配we

boolean we = str.matches("we");

System.out.println(we);//输出false

}

字符串拆分

String str="we are happy";

//按照指定字符拆分

String[] strArr = str.split("\\s");

System.out.println(Arrays.toString(strArr));//[we, are, happy]

字符串替换

String str="we are happy";

//按照规则进行替换

String strreplace = str.replaceAll("happy", "haha");

System.out.println(strreplace);//we are haha

2.使用类

String str="we are happy";

//定义正则表达式

String regex="happy";

Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher(str);

boolean matches = matcher.matches();

boolean isfind = matcher.find();

if(isfind){

matcher.start();//开始索引

matcher.end();//结束索引

}

//正则表达式匹配 匹配电话号码

Pattern pattern = Pattern.compile("^(\\d{3,4})\\-(\\d{6,8})$");

Matcher matcher = pattern.matcher("010-12345678");

if (matcher.matches()){

String whole = matcher.group(0);

String group1 = matcher.group(1);

String group2 = matcher.group(2);

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值