javase笔记3----正则表达式

正则表达式

简介

正则表达式(Regular Expressions),是一个特殊的字符串,可以对普通的字符串进行校验检测等工作,校验一个字符串是否满足预设的规则。

基本语法

字符集合

[] : 表示匹配括号里的任意一个字符。
[abc] :匹配a 或者 b 或者 c
[^abc] : 匹配任意一个字符,只要不是a,或b,或c 就表示匹配成功
[a-z] : 表示匹配所有的小写字母的任意一个。
[A-Za-z] :表示匹配所有的小写字母和大写字母的任意一个。
[a-zA-Z0-9]:表示匹配所有的小写字母和大写字母和数字的任意一个。
[a-z&&[^bc]] :表示匹配所有的小写字母除了b和c, 只要匹配上就是true.

System.out.println("a".matches("[abcdefg]"));
String regex = "[^hg]";
String str = "a";
System.out.println(str.matches(regex);//true

预定义字符集

\d:  用于匹配数字字符中的任意一个    相当于[0-9]
\w:  匹配单词字符中的任意一个        单词字符就是a-zA-Z0-9
\D:   用于匹配非数字字符中的任意一个  相当于[^0-9]
\W:   用于匹配非单词字符中的任意一个
\s:  用于匹配空格,制表符,退格符,换行符等中的任意一个
\S:   用于匹配非空格,制表符,退格符,换行符等中的任意一个
. :  用于匹配任意一个字符

System.out.println("c".matches("[\\w]"));
System.out.println("a".matches("\\w"));
System.out.println("+".matches("."));

数量词

X?   :匹配0个或1个
X*   :匹配0个或1个以上
x+   :匹配1个以上
X{n} :匹配n个
X{m,}:匹配m个以上
X{m,n}:匹配m~n个

//匹配密码,要求密码必须是8位的数字或字母组合
System.out.println("123abc45".matches("[a-zA-Z0-9]{8}")); //true
System.out.println("123abc".matches("[a-zA-Z0-9]{8})); //false
System.out.println("123abc456".matches("[a-zA-Z0-9]{8}));//false
//匹配用户名: 用户名是由字母数字和下划线组成,5-8位
System.out.println("_abc123".matches("\\w{5,8}")); //true

分组

在正则表达式上可以使用()来进行对一些字符分组,并可以使用逻辑运算符|来进行选择匹配

String regex1 = "(13|18|15)(7|8|9)[\\d]{8}";
System.out.println("13811110000".matches(regex1));//true
System.out.println("13311110000".matches(regex1)); //false

^和$

^:表示严格从头匹配
$: 表示匹配到结尾

常用方法

1. boolean matches(String regex)
  判断this字符串是否匹配正则表达式regex
2. String[] split(String regex) 
  对this使用匹配上正则表达式的子串进行切分成字符串数组
3. replaceAll()  

String username = "lily123";
String regex = "[a-zA-Z0-9[[\\w]{7,9}";
//检查用户名是否匹配
boolean flag = username.matches(regex);
if(flag){
    System.out.println("用户名可用");
}else{
    System.out.println("用户名不可用");
}
String str = "hello123world456welcome789";
//请使用数字将其切分成字符串数组
String regex1 = "\\d+";
String[] arr = str.split(regex1);
System.out.println(Arrays.toString(arr)); //[hello,word,welcome]
System.out.println(arr.length); //3
str = "888aaa9bbb10ccc";
arr = str.split(regex1);
System.out.println(Arrays.toString(arr));//[,aaa,bbb,ccc]
System.out.println(arr.length);//4
str = "123abc234def235hhh";
arr = str.split("3");
System.out.println(Arrays.toString(arr)); //[12,abc2,4def2,5hhh]
System.out.println(arr.length); //4
String info = "no zuo no die";
String newInfo = info.replaceAll("no","yes");
System.out.println(newInfo);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值