正则表达式的使用和理解
1、理解
正则表达式(Regular Expression,简称 regex 或 regexp)是一种强大的文本处理工具,它使用一种特定的模式来描述、匹配和操作文本字符串。正则表达式可以被用来检查一个字符串是否匹配某种模式,或者从一个字符串中提取特定的信息。
2、应用场景
1、处理字符串的替换
package com.xx.regex;
public class Test01 {
/**
* 知识点:正则表达式
* 含义:用来描述或者匹配一系列符合某个语句规则的字符串
*
* 案例:把一个字符串中带电话号码替换成130****1111
*/
public static void main(String[] args) {
String str = "小红13012341111 小绿15112342222";
String regex = "(1\\d{2})(\\d{4})(\\d{4})";
str = str.replaceAll(regex , "$1****$3");
System.out.println(str);
}
}
2、处理字符串的校验
package com.xx.regex;
public class Test02 {
/**
* 知识点:正则表达式
* 含义:用来描述或者匹配一系列符合某个语句规则的字符串
*
* 案例:校验QQ邮箱
*/
public static void main(String[] args) {
String email = "144558498011@qq.com";
String regex = "\\d{4,11}@qq.com";
boolean matches = email.matches(regex);
System.out.println(matches);
}
}
3、处理字符串的分割
package com.xx.regex;
public class Test03 {
/**
* 知识点:正则表达式
* 含义:用来描述或者匹配一系列符合某个语句规则的字符串
*
* 案例:分割路径
*
* 小结:利用正则表达式处理字符串的分割
*/
public static void main(String[] args) {
String str = "C:\\资源\\日韩\\波多野结衣.avi";
String regex = ":?\\\\";// :\\ 或 \\
String[] split = str.split(regex);
for (String string : split) {
System.out.println(string);
}
}
}
4、爬数据
package com.xx.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test04 {
/**
* 知识点:正则表达式
* 含义:用来描述或者匹配一系列符合某个语句规则的字符串
*
* 案例:Pattern+Matcher 找到前端代码中的图片路径
*/
public static void main(String[] args) {
String str = "<img src ='ert/axa.jpg'/><div><div/> <input type='image' src='submit.gif' /><img src='bxb.jpg'/>";
//正则表达式的字符串
String regex = "<img\\b[^>]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg)\\b)[^>]*>";
//获取正则表达式对象
Pattern pattern = Pattern.compile(regex);
//匹配结果
Matcher matcher = pattern.matcher(str);
//循环遍历
while(matcher.find()){//查询匹配结果
String group = matcher.group(2);//获取匹配结果(第2组-第二个小括号里的数据)
System.out.println(group);
}
}
}