我有一个简单的要求,在HTML中提取文本。假设HTML是使用正则表达式提取HTML的部分
<h1>hello</h1> ... <img moduleType="calendar" /> ...<h2>bye</h2>
我想把它转换成三个部分
<h1>hello</h1>
<img moduleType="calendar" />
<h2>bye</h2>
目的是两类,简单的HTML和特殊标签来提取文本与< IMG moduleType = “日历”。
我有一个简单的要求,在HTML中提取文本。假设HTML是使用正则表达式提取HTML的部分
<h1>hello</h1> ... <img moduleType="calendar" /> ...<h2>bye</h2>
我想把它转换成三个部分
<h1>hello</h1>
<img moduleType="calendar" />
<h2>bye</h2>
目的是两类,简单的HTML和特殊标签来提取文本与< IMG moduleType = “日历”。
这取决于您使用的语言和上下文。我在CMS上做了类似的事情,我的方法是首先查找标签,然后查找属性。
获取广告代码
"<img (.*?)/>"
然后,我通过结果搜索如果你想找到的所有属性,你可以很容易改变的明确所有权,正则表达式[AZ]针对特定属性
'title="(.*?)"'
,或非空白字符,然后遍历这些结果。
对抗downvotes你会得到 - 欢迎来到SO; - )在答案中包含已知问题/限制。使用正则表达式进行HTML解析几乎总是被禁止的。 – 2010-04-22 20:02:29
不要那样做; HTML可以用很多美丽的方式打破。改为使用beautiful soup。
我实际上试图做类似的事情,因为asp.net编译器将标记编译成服务器控件树,正则表达式被asp.net编译器大量使用。我有一个临时解决方案,虽然不好,但似乎没问题。
//string source = "<h1>hello</h1>"; string source = "<h1>hello<img moduleType=\"calendar\" /></h1> <p> <img moduleType=\"calendar\" /> </p> <h2>bye</h2> <img moduleType=\"calendar\" /> <p>sss</p>"; Regex exImg = new Regex("(.+?)(<img.*?/>)"); var match = exImg.Match(source); int lastEnd = 0; while (match.Success) { Console.WriteLine(match.Groups[1].Value); Console.WriteLine(match.Groups[2].Value); lastEnd = match.Index + match.Length; match = match.NextMatch(); } Console.WriteLine(source.Substring(lastEnd, source.Length - lastEnd));
/我叹了口气......另一个“如何解析HTML与正则表达式”的问题... – 2010-04-22 19:11:43
你在什么语言编码?有可能比正则表达式更好的解决方案,许多语言都有DOM解析器。另外,您可能想要接受其他一些问题的答案,以提高未来答案的质量和数量。 – 2010-04-22 19:12:34
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – 2010-04-22 19:16:37