2016-07-25 101 views
0

我有這樣的HTML代碼中的字符串:拆分HTML鏈接標籤

Hello world 
    <img src="mypicture.png" /> 
    <p>Some text in a tag</p> 
    <a href="http://www.google.fr">Link to google</a> Some Text <a href="http://www.yahoo.fr">Link to yahoo</a> End of line 
    <p>Some text in a tag</p> 
    <a attribute="some value" href="http://www.apple.com">Link to apple</a> 
    Some text 

我想這個字符串轉換成數組:

0 => Hello world 
    <img src="mypicture.png" /> 
    <p>Some text in a tag</p> 
    <a href=" 

    1 => http://www.google.fr 

    2 => ">Link to google</a> Some Text <a href=" 

    3 => http://www.yahoo.fr 

    4 => ">Link to yahoo</a> End of line 
    <p>Some text in a tag</p> 
    <a attribute="some value" href=" 

    5 => http://www.apple.com 

    6 => ">Link to apple</a> 
    Some text 

我已經試過這個正則表達式。它工作正常提取的聯繫,但我不設法建立我的陣列...

<a (.*?)href=(.*?)\"(.+?)\"(.*?)> 
+0

嘗試樂趣:'(?<= * href = \「)([^」] +)(?= \「[^>] *>) –

+0

with regex.match? – Bob5421

+0

使用'Regex.Split '。 –

回答

0

您可以鏈接以及之前剛剛添加的東西來捕捉任何和一切:

([\W\w]*?)(?:(<a .*?href=.*?\")(.+?)(?=\")|$)

  • 獲取的每一個字符,直到...
  • 找到鏈接:
    • 獲取ŧ他連接起來,href值(基本代碼)
    • 獲取字符到下一個報價
  • 文本的結束被找到(網址)

然後你只需要逐步完成每個匹配,並將pre + link添加到陣列,並將url添加到陣列中。