赞
踩
【部分参考】:https://blog.csdn.net/qi923701/article/details/79180756
(参考的例子中代码是没有考虑到换行符的)
【链表形式】:
/** * 获取指定HTML标签的指定属性的值 * * @param source * 要匹配的源文本 * @param element * 标签名称 * @param attr * 标签的属性名称 * @return 属性值列表 */ public static String match(String source, String element, String attr) { String result = ""; // 原博主代码是这样的 // String reg = "<" + element + "[^<>]*?\\s" + attr + "=['\"]?(.*?)['\"]?(\\s.*?)?>"; String reg = "<" + element + "[^<>]*?\\s" + attr + "=['\"]?(.*?)['\"]{1}(\\s.*?)?>?"; Matcher m = Pattern.compile(reg).matcher(source); while (m.find()) { result = m.group(1); } return result; } public static void main(String[] args) { String source = "<input type=\"submit\" value=\"上传\" style=\"" + "\nwidth: 40%;\nheight: 40px;\nbackground-color: #558afc;\nborder: none;\">" + "<input type=\"submit\" value=\"\" style=\"" + "\nwidth: 40%;\nheight: 40px;\nbackground-color: #558afc;\nborder: none;\">" + "<input type=\"submit\" value=\"删除\" style=\"" + "\nwidth: 40%;\nheight: 40px;\nbackground-color: #558afc;\nborder: none;\">"; String regEx_input = "<input[^<>]*?\\svalue=['\"]?(.*?)['\"]{1}(\\s.*?)?>?"; System.out.println(match(source, "input", "value")); }
【输出结果】:
【单个形式】(获取input标签中的value值):
public static void main(String[] args) {
String source = "<input type=\"submit\" value=\"上传\" style=\""
+ "\nwidth: 40%;\nheight: 40px;\nbackground-color: #558afc;\nborder: none;\">"
+ "<input type=\"submit\" value=\"\" style=\""
+ "\nwidth: 40%;\nheight: 40px;\nbackground-color: #558afc;\nborder: none;\">"
+ "<input type=\"submit\" value=\"删除\" style=\""
+ "\nwidth: 40%;\nheight: 40px;\nbackground-color: #558afc;\nborder: none;\">";
String regEx_input = "<input[^<>]*?\\svalue=['\"]?(.*?)['\"]{1}(\\s.*?)?>?";
Pattern p = Pattern.compile(regEx_input);
Matcher m = p.matcher(source); // 获取 matcher 对象
while (m.find()) {
String group = m.group(1);
if (!group.trim().isEmpty())
System.out.println(group);
}
【输出结果】:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。