正则表达式之搜索
正则表达式可以用来从字符串中搜索可匹配的字符串。
例如:从下面文字中搜索出所有的Email地址。
我是小亮点科技,我的邮箱是49059372@qq.com。我们在学习Java,这里有一个测试邮箱test@sina.com。学会了正则表达式就可以找到所有的邮箱,java_study@163.com。
package regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* [简要描述]:搜索邮箱地址
* [详细描述]:
*
* @author Smalight Lv
* @version 1.0, 2021/5/1 01:05
* @since JDK 1.8
*/
public class EmailRegex {
public static void main(String[] args) {
String str = "我是小亮点科技,我的邮箱是49059372@qq.com。我们在学习Java,这里有一个测试邮箱test@sina.com。学会了正则表达式就可以找到所有的邮箱,java_study@163.com。";
Pattern pattern = Pattern.compile("[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
System.out.println(str.substring(matcher.start(), matcher.end()));
}
}
}
运行结果:
49059372@qq.com
test@sina.com
java_study@163.com
matcher.start()是搜索到匹配的子串的起始位置。
matcher.end()是搜索到匹配的子串的结束位置。