如何解决用于捕获<div>标记周围的文本的正则表达式?
| 我有一堆需要标题和描述文本的产品,因此我可以将它们放入看起来像这样的查询中: 插入uc_products(标题,描述)值 (\'Lafayette RK-820 4磁道立体声磁带座\',\“操作和维修手册,包括零件清单和示意图\'), 该信息当前收集在一些div标签中:<div class=\"radio-product-wrap\">
<div class=\"radio-product-image\">
</div>
<div class=\"radio-product-title\">
<p>Lafayette RK-820 4 track stereo tape deck</p>
</div>
<div class=\"radio-product-desript\">
<p>Operation and service manual,includes parts list &amp; schematic</p>
</div>
<div class=\"radio-cart-66-wrap\">
[add_to_cart item=\"L-1\"]
</div>
</div>
我将如何编写正则表达式以获取信息?
解决方法
使用哪种目标语言?还是只需要正则表达式本身?
请注意,正则表达式仅在提取HTML文档中定义明确的部分时才有用,并且不能用于一般地解析HTML。
如果您只需要一个正则表达式,则可以使用:
<div\\ class=\"radio-product-title\"> # literal div tag with class
[^<]* # any chars that are not \'<\'
<p> # literal \'<p>\' tag
\\s* # optional leading spaces
([^<]+?) # one or more chars that are not \'<\',# captured in to group #1
# (non-greedy)
\\s* # optional trailing spaces
<\\/p> # literal \'</p>\' tag
[^<]* # any chars that are not \'<\'
<\\/div> # literal \'</div>\' end tag
[^<]* # any chars that are not \'<\'
<div\\ class=\"radio-product-desript\"> # literal div tag with class
[^<]* # any chars that are not \'<\'
<p> # literal \'<p>\' tag
\\s* # optional leading spaces
([^<]+?) # one or more chars that are not \'<\',# captured in to group #2
# (non-greedy)
\\s* # optional trailing spaces
<\\/p> # literal \'</p>\' tag
同样的东西没有评论:
<div\\ class=\"radio-product-title\">[^<]*<p>\\s*([^<]+?)\\s*<\\/p>[^<]*<\\/div>[^<]*<div\\ class=\"radio-product-desript\">[^<]*<p>\\s*([^<]+?)\\s*<\\/p>
此正则表达式假定在<p>
和</p>
标签之间没有\'<\'字符。如果不是这种情况,则需要进行修订。
根据您的目标语言,您可能需要告诉正则表达式引擎在处理过程中将源字符串视为“单行”。
完成后,match [1]将包含标题,match [2]将包含描述。
编辑警告提示...
虽然确实不能使用正则表达式可靠地解析任意HTML文档,但它们是从此类文档IFF中提取元素的绝佳工具:
所有文档的格式均相同。
目标元素定义明确,易于识别。
警告人们在这种情况下提取数据时不要使用正则表达式是屈服于教条而不加理解。
, 这应该工作:
<div class=\"radio-product-title\">.*?<p>(?<Title>.*?)</p>.*?</div>.*?<div class=\"radio-product-desript\">.*?<p>(?<Description>.*?)</p>.*?</div>
您需要从比赛中捕获两个命名的组Title
和Description
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。