Home  >  Article  >  Java  >  Java method to obtain the specified attribute value of a specified HTML tag based on regular expressions

Java method to obtain the specified attribute value of a specified HTML tag based on regular expressions

高洛峰
高洛峰Original
2017-01-22 14:46:161375browse

本文实例讲述了Java基于正则表达式获取指定HTML标签指定属性值的方法。分享给大家供大家参考,具体如下:

有时可能会有这样的需求,从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标签的指定属性的值
 * @ProjectName stuff
 * @Author mikan
 * @FullName com.mmq.regex.MatchHtmlElementAttrValue.java
 * @JDK 1.6.0
 * @Version 1.0
 */
public class MatchHtmlElementAttrValue {
  /**
   * 获取指定HTML标签的指定属性的值
   * @param source 要匹配的源文本
   * @param element 标签名称
   * @param attr 标签的属性名称
   * @return 属性值列表
   */
  public static List match(String source, String element, String attr) {
    List result = new ArrayList();
    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 = "aaabbb";
    List list = match(source, "a", "title");
    System.out.println(list);
  }
}

希望本文所述对大家java程序设计有所帮助。

更多Java基于正则表达式获取指定HTML标签指定属性值的方法相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn