马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
正则表达式
简介
正则表达式(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);
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |