In diesem Artikel wird die Methode des Java beschrieben, das die angegebenen HTML -Tags erhält und Attributwerte angeben, basierend auf regulären Ausdrücken. Teilen Sie es für Ihre Referenz wie folgt weiter:
Manchmal kann es eine solche Anforderung geben. Das Erhalten des angegebenen Attributwerts des angegebenen Tags von der HTML-Seite kann durch die Parsen von Drittbibliotheken erhalten werden, dies ist jedoch relativ problematisch!
Wenn Sie reguläre Ausdrücke verwenden, wird es einfach. Der Code ist wie folgt:
package com.mmq.regex;import java.util.ArrayList;import java.util.List;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * @use Get the value of the specified attribute of the specified HTML tag* @ProjectName stuff * @Author mikan * @FullName com.mmq.regex.MatchHtmlElementAttrValue.java * @JDK 1.6.0 * @Version 1.0 */public class MatchHtmlElementAttrValue { /** * Get the value of the specified attribute of the specified HTML tag* @param source source source text to match* @param element tag name* @param attr attribute name* @return attribute name of the tag* @Return Attributwertliste*/ public staticlist <string> Übereinstimmung (String -Quelle, String -Element, String attr) {list <string> result = new ArrayList <string> (); String reg = "<" + element + "[^<>]*? // s" + attr + "= ['/"]? (.*?) ['/"]? (// s.*?)?>"; Matcher M = musters.comPile (Reg) .Matcher (Quelle); while (m.find ()) {String r = m.group (1); result.add (r); } Rückgabeergebnis; } public static void main (String [] args) {String source = "<a title = China Sports News href = ''> aaa </a> <a title = 'peking Daily' href = ''> BBB </a>"; List <String> list = Match (Quelle, "a", "title"); System.out.println (Liste); }}PS: Hier sind zwei sehr bequeme reguläre Ausdruckswerkzeuge für Ihre Referenz:
JavaScript regulärer Ausdruck Online -Test -Tool:
http://tools.vevb.com/regex/javaScript
Regelmäßiger Ausdruck Online -Generierungstool:
http://tools.vevb.com/regex/create_reg
Ich hoffe, dieser Artikel wird für Java -Programme aller hilfreich sein.