2015-10-19 65 views
0

我想找到一些共同的html标签内/属性正则表达式来找到标签/属性是HTML代码

<a href="xyz">this is an example of an href</a> 

我想找到的“href”的第一个实例,因为它是HTML代码中使用,但不是第二个实例,因为它只是html。

我可以尝试在“< ...>”分隔符内寻找代码,但有两个问题,大多数浏览器将允许'<',即使它应该是“GT”。

the letter A is < than the letter B 

<a name="24 is > than 12">this is an example of an href</a> 

这样我就可以放心地我找里面的HTML属性,即使它并不总是100%使用正则表达式格式正确的代码?

+2

请记住这一点http://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not – deW1

+0

我不_寻找一个html解析器,我只想寻找一个单词“href”,并告诉它是否在html标签中使用,或者它是否仅用作文本。 – FFMG

+2

也看到这个答案http://stackoverflow.com/a/1732454/597607 –

回答

0

正则表达式<\s*a\s+(?:\w+\s*=\s*(?:"[^"]*"|'[^']*')\s+)*href\s*=\s*(?:"([^"]*)"|'([^']*)')

将匹配字符串#1,4,5,7,8

1: <a href="xyz">this is an example of an href</a> 

2: <a name="24 is > than 12">this is an example of an href</a> 

3: <a name="24 is > than 12">this is an example of an href="xyz"</a> 

4: <a href="xyz" name="24 is > than 12">this is an example of an href</a> 

5: <a name="24 is > than 12" href="xyz">this is an example of an href</a> 

6: <a name="24 is > than 12 href='xyz'">this is an example of an href</a> 

7: <a name="24 is > than 12 href='xyz'" href="xyz">this is an example of an href</a> 

8: <a name="24 is > than 12 href='xyz'" href="xyz">this is an example of an href="xyz"</a> 

经由Regex Online测试。

如果使用'报价,您必须使用第二个匹配组(matches[2])。