需求
搜索字符串(下文称主串)中所有符合某正则表达式的子串,并得到所有子串的文字、位置、长度。
需求案例
一段长文字:头部123456@qq.com中间的文字吧啦吧啦balabala@sina.com.cn快结束了吧啦吧啦my_mail@163.com测试相同子串123456@qq.com,得到其中所有的邮箱。
难点
1、String类涉及正则表达式的常用方法中,包含匹配、分割、替换,难以实现需求;
2、主串中包含的符合条件的子串,可能文字完全相同,用 主串.indexOf(子串) 的方式,得不到正确索引。
难点解决思路
1、利用Pattern类(包:java.util.regex.Pattern)加Matcher类(包:java.util.regex.Matcher)实现搜索;
2、遍历过程中,每次搜索到结果后,截串,让 主串.indexOf(子串) 避开之前的串。
代码
String originalString = "头部123456@qq.com中间的文字吧啦吧啦balabala@sina.com.cn快结束了吧啦吧啦my_mail@163.com测试相同子串123456@qq.com";
String searchString = originalString;
String regexString = "[a-zA-Z0-9_]+@[0-9a-z]+(\\.[a-z]+)+";
Pattern datePattern = Pattern.compile(regexString);
Matcher dateMatcher = datePattern.matcher(searchString);
int beEndIndex = 0;
while(dateMatcher.find()) {
String subString = dateMatcher.group();
System.out.print("子串:"+subString+" ");
int subIndex = searchString.indexOf(subString);
System.out.print("位置:"+(subIndex + beEndIndex)+" ");
int subLength = subString.length();
System.out.println("长度:"+subLength);
beEndIndex = subIndex + subLength + beEndIndex;
searchString = originalString.substring(beEndIndex);
dateMatcher = datePattern.matcher(searchString);
}
System.out.println("end");
输出结果
备注
1、为什么会有这种需求?
例如在安卓开发中,需要把这段文字中的所有类似"123456@qq.com"的邮箱地址换成"点击跳转"四个字,或者把主串中所有类似"www.baidu.com"的网址的文字颜色换成蓝色以达到看上去可以点击的效果;
2、欢迎指正、交流。