2012-03-23 62 views
0

我需要在html頁面內抓取內聯腳本標記。 正則表達式最終將從c#驅動。 現在我正在使用Expresso進行測試。正則表達式在html中捕獲多行腳本標記

現在下面是最好的:

.*<script.*\r\n(.*\r\n)*\s*</script> 

  • .*<script抓script標籤
  • .*\r\n抓什麼,直到行末的
  • (.*\r\n)*趕上其他線路劇本
  • \s*</script>捕捉結束腳本,之前有任何縮進

它抓住第一個標記之間的所有東西,包括html和其他腳本標記。

+6

你用正則表達式解析HTML有問題嗎? [顏色我感到驚訝](http://stackoverflow.com/a/1732454/424509)! – CanSpice 2012-03-23 17:30:30

+1

如果你打算在C#中使用這個,請嘗試http://htmlagilitypack.codeplex.com/ – Stephen 2012-03-23 17:40:07

+1

@CanSpice - 我認爲這篇文章的受歡迎程度已經結束了「我可以將HTML的正則表達式」問題。可悲的是沒有。 – David 2012-03-23 18:45:17

回答

4

同一行上的兩個腳本會破壞你的正則表達式。試着在你的問題的網頁來源。

解析HTML與正則表達式是不是一個很好的主意(存在於你的問題的評論這answers爲什麼<center>不能持有鏈接);改爲使用HTML分析器。

下面的代碼片段通過使用HtmlAgilityPack選擇<script>節點:

var doc = new HtmlDocument(); 
doc.Load(html); 
var scripts = doc.DocumentNode.SelectNodes("//script"); 

這是不是比正則表達式simplier?

1

如何實現「點匹配所有」,用簡單的東西:

<script\b[^>]*>(.*?)</script> 

記住匹配是不一樣的拍攝。這應該捕獲($ 1)標籤之間的內容。我沒有使用http://regexpal.com/

快速測試在Eclipse中使用bosinski.com/regex(我知道這不是C#)這裏是我的測試文件(後面的結果):

<html> 
<SCRIPT LANGUAGE="JavaScript"><!-- 
function demoMatchClick() { 
    var re = new RegExp(document.demoMatch.regex.value); 
    if (document.demoMatch.subject.value.match(re)) { 
    alert("Successful match"); 
    } else { 
    alert("No match"); 
    } 
} 
// --> 
</SCRIPT> 
<script language="fred"> 
this is the second set of code 
</script> 
</html> 

正則表達式匹配的結果:

Found 2 match(es): 

start=8, end=275 
Group(0) = <SCRIPT LANGUAGE="JavaScript"><!-- 
function demoMatchClick() { 
    var re = new RegExp(document.demoMatch.regex.value); 
    if (document.demoMatch.subject.value.match(re)) { 
    alert("Successful match"); 
    } else { 
    alert("No match"); 
    } 
} 
// --> 
</SCRIPT> 
Group(1) = <!-- 
function demoMatchClick() { 
    var re = new RegExp(document.demoMatch.regex.value); 
    if (document.demoMatch.subject.value.match(re)) { 
    alert("Successful match"); 
    } else { 
    alert("No match"); 
    } 
} 
// --> 

start=277, end=344 
Group(0) = <script language="fred"> 
this is the second set of code 
</script> 
Group(1) = 
this is the second set of code 
1

根據你問的人,你有不同的問題。無論是你的問題是,你使用HTML的正則表達式,或量詞太貪婪。

我不知道你想解決的問題,但機會很好,你的解決方案應該是使用html解析器。

如果你想堅持使用正則表達式,那麼使用量詞*?的不確定版本。然後,您的正則表達式將是這個樣子

.*<script.*\r\n(.*\r\n)*?\s*</script> 

,這意味着需要直到第一結束標記,將匹配的行數更少。

0

Try this

<(?<tag>script*)[^>]*>(?<content>.*?)<\/\k<tag>> 

一詞取代script<tag>與其他元素的名稱後,你可以使用它的人太多。