![](/img/trans.png)
[英]extract links (URLs), with nokogiri in ruby, from a href html tags?
[英]Extract links from BBcode with Ruby
從BBcode [code] ... [/ code]部分提取鏈接的簡單方法/正則表達式是哪一個? 所有鏈接均以http://開頭,並以\\ n或[/ code]標記結尾,最后可能有一些空格或其他空格字符。
一個[code]部分可以包含多個鏈接/代碼標簽:
[code]http://example1.com
http://example2.com
http://example3.com
[code]
有時還會出現多個連續的[code]部分:
[code]http://example4.com
http://example5.com [/code]
[code]http://example6.com[/code]
[code]
http://example7.com
http://example8.com[/code]
我想從上面定義的部分中獲取所有鏈接,並以簡單的展平數組形式進行,但是我無法為scan方法解決正確的正則表達式。
試試這個:
data = '[code]http://example4.com
http://example5.com [/code]
[code]http://example6.com[/code]
[code]
http://example7.com
http://example8.com[/code]'
p data.split(/\[\/*code\]/)
.flat_map{|el| el.split(/\s+/)}
.reject(&:empty?)
輸出:
#=> ["http://example4.com", "http://example5.com", "http://example6.com", "http://example7.com", "http://example8.com"]
您可以嘗試以下方法:
測試字符串:
bbcode = <<EOF
[code] xxxxx
xxxxx
http://example1.com
http://example2.com
http://notme.org abcd
http://example3.com
[/code]
[code]xxxx[/code]
http://notme.com
[code]http://example4.com
http://example5.com[/code]
[code]http://example6.com [/code]
[code]
http://example7.com
http://example8.com[/code]
EOF
正則表達式:
pattern = Regexp.new('
# Definitions
(?<url> http://[^\[\s]++ ){0}
(?<open> \[code\] ){0}
(?<close> \[/code\] ){0}
(?<ws> [^\S\n]++ ){0}
(?<other> \g<ws>?+
(?> (?!\g<url>) | \g<url> \g<ws> )
[^\[\n]++ ){0}
(?<end> \g<ws>?+ (?> \n | \g<close> ) ){0}
# Pattern
(?> \g<open> | \G (?<! \g<close> ) )
(?> \g<other>?+ \n++ )* \g<ws>?+ \g<url> \g<end> ',
Regexp::EXTENDED | Regexp::IGNORECASE)
bbcode.scan(pattern) do |link, tag|
puts "#{link}\n"
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.