java正則表達式獲取指定HTML標簽的指定屬性值


 

package com.mmq.regex;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @use 獲取指定HTML標簽的指定屬性的值
 * @FullName com.mmq.regex.MatchHtmlElementAttrValue.java </br>
 * @JDK 1.6.0 </br>
 * @Version 1.0 </br>
 */
public class MatchHtmlElementAttrValue {
    
    /**
     * 獲取指定HTML標簽的指定屬性的值
     * @param source 要匹配的源文本
     * @param element 標簽名稱
     * @param attr 標簽的屬性名稱
     * @return 屬性值列表
     */
    public static List<String> match(String source, String element, String attr) {
        List<String> result = new ArrayList<String>();
        String reg = "<" + element + "[^<>]*?\\s" + attr + "=['\"]?(.*?)['\"]?\\s.*?>";
        Matcher m = Pattern.compile(reg).matcher(source);
        while (m.find()) {
            String r = m.group(1);
            result.add(r);
        }
        return result;
    }
    
    public static void main(String[] args) {
        String source = "<a title=中國體育報 href=''>aaa</a><a title='北京日報' href=''>bbb</a>";
        List<String> list = match(source, "a", "title");
        System.out.println(list);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM