Java正则表达式从html中删除标记
上面的文本是我的html字符串,需要提取头、子、开始日期和结束日期的值。我使用Jsoup来提取值,但我对非html元素标记有问题。API要么跳过这些元素,要么添加一个最初不存在的结束标记 因此,我的想法是用替换非html元素标记,然后使用Jsooup提取值Java正则表达式从html中删除标记,java,regex,jsoup,Java,Regex,Jsoup,上面的文本是我的html字符串,需要提取头、子、开始日期和结束日期的值。我使用Jsoup来提取值,但我对非html元素标记有问题。API要么跳过这些元素,要么添加一个最初不存在的结束标记 因此,我的想法是用替换非html元素标记,然后使用Jsooup提取值 任何建议???您可能希望参考解析HTML文档。您可以使用此api提取和处理数据。您可以使用此正则表达式提取内容: <table><tr><td>HEADER</td><td>Head
任何建议???您可能希望参考解析HTML文档。您可以使用此api提取和处理数据。您可以使用此正则表达式提取内容:
<table><tr><td>HEADER</td><td>Header Value <supporting value></td></tr><tr><td>SUB</td><td>sub value. write to <test@gmail.com></td></tr><tr><td>START DATE</td><td>11/23/ 2016</td></tr><tr><td>END DATE</td><td>11/23/2016</td></tr></table>
假设标记布局始终看起来相同
虽然不能使用正则表达式解析完整的HTML文档,因为它不是上下文无关语言,但实际上可以进行类似的部分提取。找到了解决方案,使用模式/]+从HTML字符串中获取所有标记 然后用<>替换除TR和TD之外的所有标签。当我使用Jsoup解析文本时,我得到了所需的值 请在下面查找代码
/<td>[^<]*<([^>]*)><\/td>/
}必须尊重传统:你在寻求解决方案,但你没有很好地定义问题。您在寻找什么模式?@sp00m您不能使用正则表达式来解析整个html文档,但在这种情况下,只能提取一些遵循定义良好的模式的值。@WiktorStribiżew这不太一样。这些不是有效的HTML标记。这不是一个好主意。请参阅。它不是有效的HTML。@shmosel是无效的HTML标记。另一个也一样。@shmosel在做POC时为我工作。我确实使用了Jsoup,当我使用Jsoup解析html字符串时,会自动添加结束标记和。因此,我的计划是找到一个模式并替换非html元素。之后,我将使用Jsoup进行解析。
public class JsoupParser2 {
public static void main(String args[]) {
String orginalString, replaceString = null;
HashSet<String> tagSet = new HashSet<String>();
HashMap<String,String> notes = new HashMap<String,String>();
Document document = null;
try{
//Read the html content as String
File testFile = new File("C:\\test.html");
List<String> content = Files.readLines(testFile, Charsets.UTF_8);
String testContent = content.get(0);
//Get all the tags present in the html content
Pattern p = Pattern.compile("<([^\\s>/]+)");
Matcher m = p.matcher(testContent);
while(m.find()) {
String tag = m.group(1);
tagSet.add(tag);
}
//Replace the tags thats non-html
for(String replaceTag : tagSet){
if(!"table".equals(replaceTag) && !"tr".equals(replaceTag) && !"td".equals(replaceTag)){
orginalString = "<"+replaceTag+">";
replaceString = "<"+replaceTag+">";
testContent = testContent.replaceAll(orginalString, replaceString);
}
}
//Parse the html content
document = Jsoup.parse(testContent, "", Parser.xmlParser());
//traverse through TR and TD to get to the values
//store the values in the map
Elements pTags = document.select("tr");
for (Element tag : pTags) {
if(!tag.getElementsByTag("td").isEmpty()){
String key = tag.getElementsByTag("td").get(0).text().trim();
String value = tag.getElementsByTag("td").get(1).html().trim();
System.out.println("KEY : "+key); System.out.println("VALUE : "+value);
notes.put(key, value);
System.out.println("==============================================");
}
}
}catch (IOException e) {
e.printStackTrace();
}catch(IndexOutOfBoundsException ioobe){
System.out.println("ioobe");
}
}