iApp技术文章

Java使用正则匹配网页上的资源

2018-11-24  本文已影响0人  抹茶NightSky

大家好我是抹茶,今天给大家带来java的正则表达式的使用。

String类中的三个基本操作使用正则:

匹配:matches()

切割: split()

替换: replaceAll()

Matcher类中常用的方法:

  boolean matches()  //是否匹配成功
  boolean find()  //查找匹配的下一个子序列
  int start()  //返回以前匹配的初始索引
  int end()  //返回最后匹配字符之后的偏移量
  Matcher reset()  //重置匹配器
  String group()  //返回由以前匹配操作所匹配的输入子序列
//利用replaceAll替换掉重复的字符
System.out.println("你你你你好好好啊".replaceAll("(.)\\1+","$1"));

//split使用正则的和replaceAll一样

正则表达式的构造摘要:

1.字符类 
[abc]        //a、b 或 c(简单类) 
[^abc]       //任何字符,除了 a、b 或 c(否定) 
[a-zA-Z]     //a 到 z 或 A 到 Z,两头的字母包括在内(范围) 
[a-d[m-p]]   //a 到 d 或 m 到 p:[a-dm-p](并集) 
[a-z&&[def]] //d、e 或 f(交集) 

2.预定义字符类 
.    //任何字符
\d   //数字:[0-9] 
\D   //非数字: [^0-9] 
\s   //空白字符:[ \t\n\x0B\f\r] 
\S   //非空白字符:[^\s] 
\w   //单词字符:[a-zA-Z_0-9] 
\W   //非单词字符:[^\w] 

3.边界匹配器 
^   //行的开头 
$   //行的结尾 
\b  //单词边界 
\B  //非单词边界 

4.Greedy 数量词 
X?       //X,一次或一次也没有 
X*       //X,零次或多次 
X+       //X,一次或多次 
X{n}     //X,恰好 n 次 
X{n,}    //X,至少 n 次 
X{n,m}   //X,至少 n 次,但是不超过 m 次 

Matcher匹配网页资源Demo

public class Main
{
    public static void main(String[] args)
    {
        String html = "<html>"+
                              "<body>"+
            "<img src=\"//fishdeep.ccxyr.top/lly/yunstream.php?filecode=a60925b303a60afdbcb862ab7d145d7f\"/>"+
            "<img src=\"//fishdeep.ccxyr.top/lly/yunstream.php?filecode=dd60ce810f05737421face90b7cc946d\"/>"+
            "<video width=\"320\" height=\"240\" controls>"+
            "<source src=\"//fishdeep.ccxyr.top/llytest/re/video.mp4\")\" type=\"video/mp4\">"+
            "</video></body>";
            Matcher m = Pattern.compile("src=\"(.*?)\"").matcher(html);
            while(m.find()){
                System.out.println("http:"+m.group(1));
            }
    }
}
上一篇下一篇

猜你喜欢

热点阅读