by luismarques · 11y ago · 0 comments
Here's a snippet of code I hacked together in D for a bot to scrape titles from pages of urls in irc messages.
matchAll(message, re_url)
.map!( match => match.captures[0] )
.map!( url => getFirst4k(url).ifThrown([]) )
.map!( content => matchFirst(cast(char[])content, re_title) )
.cache // cache to prevent multiple evaluations of preceding
.filter!( capture => !capture.empty )
.map!( capture => capture[1].idup.entitiesToUnicode )
.map!( uni_title => uni_title.replaceAll(re_ws, " ") )
.array
.ifThrown([]);
It uses D's fast compile-time regex engine to look for URLs, then it downloads the first 4k (or substitutes an empty array if there was an exception), uses regex again to look for a title, filters out any that didn't find a title, converts all the html entities to their unicode equivalents (another function I wrote), replaces excessive whitespace using regex, then returns all the titles it found (or an empty array if there was an exception). There's stuff to improve upon but compared to how I would approach it in C++ it's much nicer.