简体   繁体   中英

Extract links from BBcode with Ruby

Which is a simple method / regular expression to extract the links from a BBcode [code]...[/code] section? All links begin with http:// and end with \\n OR a [/code] tag, maybe some space or other whitespace characters at the end.

One [code] section can contains multiple links / code tag:

[code]http://example1.com
http://example2.com
http://example3.com
[code]

and sometimes multiple consecutive [code] sections can also occur:

[code]http://example4.com
http://example5.com  [/code]
[code]http://example6.com[/code]
[code]
http://example7.com
http://example8.com[/code]

I would like to get all the links from such a section defined above in a simple flattened array, but I am unable to solve the right regular expression for the scan method.

Try this one:

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?)

Output:

#=> ["http://example4.com", "http://example5.com", "http://example6.com", "http://example7.com", "http://example8.com"]

You can try this:

Test string:

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

Regex:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM