C# Regex-Can';无法从HTML元素获取特定属性
假设我有以下HTML元素:C# Regex-Can';无法从HTML元素获取特定属性,c#,regex,C#,Regex,假设我有以下HTML元素: <iframe height="100" width="200" src="https://www.stackoverflow.com/share"></iframe> <iframe height="100" width="200" src="https://www.google.com/share"></iframe> <iframe height="100" width="200" src="http
<iframe height="100" width="200" src="https://www.stackoverflow.com/share"></iframe>
<iframe height="100" width="200" src="https://www.google.com/share"></iframe>
<iframe height="100" width="200" src="https://www.yahoo.com/share"></iframe>
我想使用正则表达式来查找带有特定src
的iframe
(必须包含https://www.stackoverflow.com/share/{s}
属性,并获取此html属性中关联的其他属性
因此在本例中,正则表达式将返回:
第一组:https://www.google.com/share
第2组:100
第3组:200
我尝试了以下方法:
iframe.*src[^”“]+['']+(https:\/\/www.google.com\/share)
它会找到特定的URL并为我提供组,无论它在字符串中的什么位置
我所面临的问题是在这个问题上进行扩展,以返回HTML元素中的所有其他属性
我已尝试将以下内容添加到正则表达式:
\s+width=“(.*)”\s+height=“(.*)”
但这并不是对手
如何(可能),使用我已经形成的当前正则表达式来使用正则表达式获取剩余的属性值
更新 对于类似
http://stackoverflow.com/share/xxx
使用(请参阅):
iframe\s*(?:\s|width=“(.*)”|height=“(.*)”+src=“(.*?www.stackoverflow\.com\/share\/.*)”
对于类似http://stackoverflow.com/share
(不带/xxx
部件)使用(请参阅):
iframe\s*(?:\s | width=“(.*)”| height=“(.*)”+src=“(.*)www\.stackoverflow\.com\/share(?:/.*)”
测试个案包括:
<iframe height="100" width="200" src="https://www.youtube.com/share"></iframe>
<iframe height="100" width="200" src="https://www.youtube.com/share/xxx"></iframe>
<iframe height="100" width="200" src="https://www.stackoverflow.com/share/xxx"></iframe>
<iframe height="100" width="200" src="https://www.stackoverflow.com/share"></iframe>
<iframe height="100" width="200" src="https://www.google.com/share"></iframe>
<iframe height="100" width="200" src="https://www.google.com/share/xxx"></iframe>
<iframe height="100" width="200" src="https://www.yahoo.com/share"></iframe>
<iframe height="100" width="200" src="https://www.yahoo.com/share/xxx"></iframe>
正则表达式不是解析HTML的最佳选择。例如,请使用真正的解析器HtmlAgilityPack@FlatEric嘿-我必须为这个特定的项目使用正则表达式!你有
\K
支持吗?你可以使用iframe.*src[^”“]+['”]+\K(https:\/\/www.google.com\/share)
@mrzasa找到src
很好,我已经做到了。它找到了其他元素,如width
和height
,这是我面临的问题,但是有没有办法匹配特定的URL?它不能应用于页面上的所有I框架,只有具有特定URL的I框架我更新了文件:是不是这是你想要的吗?我还是不太确定。;-)它显示有4个结果,但应该只有一个,因为它应该只匹配url匹配的结果。。这有意义吗?因此,如果URL是stackoverflow.com/share,它将只匹配该URL,并为我提供该caseWell的属性,问题是宽度、高度和src可以是任意顺序。或者订单是固定的?还是src总是最后一个属性?是否可以分多个步骤检查字符串?像1。检查它是否为iframe,2。检查src=“(*.www\.stackoverflow\.com\/share\/.?”
,3。检查width=“(.*?”
,4。检查是否有height=“(.*)”
<iframe height="100" width="200" src="https://www.youtube.com/share"></iframe>
<iframe height="100" width="200" src="https://www.stackoverflow.com/share"></iframe>
<iframe height="100" width="200" src="https://www.google.com/share"></iframe>
<iframe height="100" width="200" src="https://www.yahoo.com/share"></iframe>