2015-10-19 138 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])。