拆分html链接标记

时间:2016-07-25 18:57:03

标签: c# regex

我在字符串中有这个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=(.*?)\"(.+?)\"(.*?)>

1 个答案:

答案 0 :(得分:0)

你也可以在链接之前添加一些内容来捕获任何内容和所有内容:

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

  • 获取每个角色直到......
  • 找到链接:
    • 获取href值的链接(基本上是您的代码)
    • 获取下一个引号(网址)
    • 的字符
  • 找到文字结尾

然后你只需要逐步完成每个匹配并将pre + link添加到数组中,并将url分别添加到数组中。