Leo Le Leo Le - 5 months ago 14
Ruby Question

Get time only in string ruby

I'm crawling data from website. And this is string I received when I parse Html by Nokogiri

"0:10\r\n (+1)\r\n "
"03:10\r\n (+1)\r\n "


How can I get only "0:10" and "03:10" ?

UPDATE

And what's different between
match
and
gsub
?

Thanks !

Answer

You shoud use the regex /\d{0,2}:\d{0,2}/ @engineer14 posted. It works, here's proof:

console.log("0:10\r\n              (+1)\r\n            ".match(/\d{0,2}:\d{0,2}/)[0])
console.log("03:10\r\n              (+1)\r\n            ".match(/\d{0,2}:\d{0,2}/)[0])

Explanation:

/ <-- open regex
\d <-- look for digit
{0,2} <-- zero or more of them
: <-- look for a colon
\d <-- look for another digit
{0,2} <-- zero or more of them
/ <-- close regex
Comments