JAVA正则表达式教程链接:菜鸟教程
java的正则表达式主要有三个类:Pattern、Matcher、PatternSyntaxException
以下实例中使用了正则表达式 .*runoob.* 用于查找字符串中是否包了 runoob 子串:
import java.util.regex.*;
class RegexExample1{
public static void main(String args[]){
String content = "I am noob " +
"from runoob.com.";
String pattern = ".*runoob.*";
boolean isMatch = Pattern.matches(pattern, content);
System.out.println("字符串中是否包含了 'runoob' 子字符串? " + isMatch);
}
}
这里会输出:字符串中是否包含了 ‘runoob’ 子字符串? true
如果是查找字符串则可以这样使用
String line = "Thisorderwashttps://www.baidu.com!OK?,absgdjsgh2345";
String pattern = "http\\w*:\\D*\\.com";
// 创建 Pattern 对象
Pattern r = Pattern.compile(pattern);
// 现在创建 matcher 对象
Matcher m = r.matcher(line);
while (m.find()) {
System.out.println("Found value: " + m.group());
}
//这里会输出https://www.baidu.com
正则表达式的替换方法有两个replaceFirst 和 replaceAll 方法
//replaceAll 使用
String line = "Thisorderwashttps://www.baidu.com!OK?,absgdjsgh2345";
String pattern = "http\\w*:\\D*\\.com";
// 创建 Pattern 对象
Pattern r = Pattern.compile(pattern);
// 现在创建 matcher 对象
Matcher m = r.matcher(line);
String string = m.replaceAll("https://www.google.com");
System.out.println(string);
//这里会输出Thisorderwashttps://www.google.com!OK?,absgdjsgh2345
//replaceFirst
String line = "Thisorderwashttps://www.google.com!OK?,absgdjsgh2345https://www.baidu.com";
String pattern = "http\\w*:\\D*\\.com";
// 创建 Pattern 对象
Pattern r = Pattern.compile(pattern);
// 现在创建 matcher 对象
Matcher m = r.matcher(line);
String string = m.replaceFirst("https://www.google.com");
System.out.println(string);
//这里会输出https://www.google.com
具体各个参数的使用方法要查询API文档