本地爬取
package MyApi.a08regexdemo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo03 {
public static void main(String[] args) {
String str="Java自从95年问世以来,经历了很多版本,目前企业中用的最多的是Java8和Java11"+"因为这两个是长期支持的版本,下一个长期支持的版本是Java17" +
"相信在不久的未来Java17也会逐渐登上历史舞台";
Pattern pattern = Pattern.compile("Java\\d{0,2}");
Matcher m = pattern.matcher(str);
private static void method1(String str) {
Pattern pattern = Pattern.compile("Java\\d{0,2}");
Matcher m = pattern.matcher(str);
网络爬取
package MyApi.a08regexdemo;
import javax.print.DocFlavor;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo04 {
public static void main(String[] args) {
URL url=new URL("http://m.sengzan.com/jiaoyu/29104.html?ivk_sa=105883i");
URLConnection conn=url.openConnection();
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream())) ;
String regex="[1-9]\\d{17}";
Pattern pattern=Pattern.compile(regex);
while((line=br.readLine())!=null){
Matcher matcher=pattern.matcher(line);
System.out.println(matcher.group());
package MyApi.a08regexdemo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regexdemoo5 {
public static void main(String[] args) {
String s="来黑马程序员学习Java" +
"手机号: 18512516758,18512508907" +
"或者联系邮箱:boniu@itcast.cn," +
"座机电话:01036517895,010-9895256" +
"热线电话:400-618-9090,400-618-4000,4006184000,4006189090";
String regex1="1[3-9]\\d{9}|(\\w+@[\\w&&[^_]]{2,6}(\\.[a-zA-Z]{2,3}){1,2})"+
"|(0\\d{2,3-?[1-9]\\d{4,9})|" +
"(400-?[1-9]\\d{2}-?[1-9]\\d{3})";
Pattern pattern=Pattern.compile("regex1");
Matcher m = pattern.matcher(s);
package MyApi.a08regexdemo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regexdemo06 {
public static void main(String[] args) {
String str="java自从95年问世以来,经历了很多版本,目前企业中用的最多的是Java8和Java11"+"因为这两个是长期支持的版本,下一个长期支持的版本是Java17" +
"相信在不久的未来Java17也会逐渐登上历史舞台";
String regex1="((?i)Java)(?=8|11|17)";
String regex2="((?i)Java)(8|11|17)";
String regex3="((?i)Java)(?:8|11|17)";
String regex4="((?i)Java)(?!8|11|17)";
Pattern pattern=Pattern.compile(regex4);
Matcher matcher = pattern.matcher(str);
String s=matcher.group();
贪婪爬取和非贪婪爬取
package MyApi.a08regexdemo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regexdemo07 {
public static void main(String[] args) {
String str="Java自从95年问世以来abbbbbbbbbbbbaaaaaaaaaaaaaaaaaa,经历了很多版本,目前企业中用的最多的是Java8和Java11"+"因为这两个是长期支持的版本,下一个长期支持的版本是Java17" +
"相信在不久的未来Java17也会逐渐登上历史舞台";
Pattern pattern=Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.group());