| n? | 匹配零个或者1个n的字符串 |
| n{x} | 匹配包含x个n的序列字符串 |
| n{x
《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享
,y} | 匹配至少x个,最多y个n的字符串 |
| n{x,} | 匹配至少x个的字符串 |
| n$ | 匹配以n结尾的字符串 |
| ^n | 匹配以n开头的字符串 |
| ?=n | 匹配其后紧接指定的n字符串 |
| ?!n | 匹配其后没有紧接指定的n字符串 |
======================================================================
一些常用的正则表达式
手机号
^1[3|4|5|7|8]\d{9}$
小数
^(-?\d+)(.\d+)?$
邮箱地址
[a-zA-Z_]{1,}[0-9]{0,}@(([a-zA-z0-9]-*){1,}\.){1,3}[a-zA-z\-]{1,}
HTML标签
/<(.)>.</\1>|<(.*) />/
中文字符
[\u4e00-\u9fa5]
QQ号
(\d+).(\d+).(\d+).(\d+)
IP
(\d+).(\d+).(\d+).(\d+)
=====================================================================
Java实现正则表达式的匹配的API:
-
Pattern 表达模式
-
Matcher 匹配器
创建方法
Pattern.compile(regEx)
忽略大小写
Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
创建方法
pattern对象.matcher(字符串)
常用方法
- boolean matches() 是否匹配完整字符串
邮箱验证案例
public static void main(String[] args) {
// 要验证的字符串
String str = “service@xsoftlab.net”;
// 邮箱验证规则
String regEx = “[a-zA-Z_]{1,}[0-9]{0,}@(([a-zA-z0-9]-*){1,}\.){1,3}[a-zA-z\-]{1,}”;
// 编译正则表达式
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(str);
// 字符串是否与正则表达式相匹配
boolean rs = matcher.matches();
System.out.println(rs);
}
常用方法
-
boolean find() 是否能在字符串中搜索到定义的内容
-
String group(String name) 返回搜索到的字符串内容
在多个img标签中搜索src的内容
String str = “<img src=“http://www.xx.com/1.jpg”><img src=“http://www.xx.com/2.jpg”>”;
Pattern pattern = Pattern.compile("<img src="(?.+?)">");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(“url”));
}
String类中的一些方法也都使用了正则表达式
如:
-
String replaceAll(String regex,String replacement)
-
boolean matches(String regex)
-
String[] split(String regex)
将数字替换为*
String str = “123456Java”;
String str2 = str.replaceAll("\d", “*”);
匹配手机号
String tel = “1567667443”;
boolean matches = tel.matches("^1[3|4|5|7|8]\d{9}$");
分割字符
String words = “中国.湖北.武汉”;
String[] strings = words.split("\.");