最近碰到在某個網站下載東西不能同時下載兩個以上的文件,為了方便下載我用了java解析網頁源碼去下載文件,其中用到了正則表達式,發個簡單的正則表達式例子。
public class PatternTest { public static void main(String[] args) { String testString = "<html><a id= 'baidu' ><a id='wangyi' ></html>"; // 符合name='baidu' 的<a>標簽. String patternString = "<//s*[a|A]([^>]*)[i|I][d|D]//s*[=]//s*['|/"](baidu)['|/"](.*?)>"; Pattern pattern = Pattern.compile(patternString, Pattern.DOTALL); Matcher ma = pattern.matcher(testString); while (ma.find()) { System.out.PRintln(ma.group()); } }}目標是提取網頁中滿足id='baidu'的<a>標簽。下面來解釋一下patternString的含義:
//s* 多個空格,<和a之間存在空格也是合法的
([^>]*) 多個非>的字符串
(.*?) 匹配盡可能短的字符串
新聞熱點
疑難解答