Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the particular part of string matching regexp in Ruby?

Tags:

ruby

I've got a string Unnecessary:12357927251data and I need to select all data after colon and numbers. I will do it using Regexp.

string.scan(/:\d+.+$/)

This will give me :12357927251data, but can I select only needed information .+ (data)?

like image 624
Simon Perepelitsa Avatar asked Jun 22 '10 15:06

Simon Perepelitsa


2 Answers

Anything in parentheses in a regexp will be captured as a group, which you can access in $1, $2, etc. or by using [] on a match object:

string.match(/:\d+(.+)$/)[1]

If you use scan with capturing groups, you will get an array of arrays of the groups:

"Unnecessary:123data\nUnnecessary:5791next".scan(/:\d+(.+)$/)
=> [["data"], ["next"]]
like image 107
mckeed Avatar answered Oct 20 '22 17:10

mckeed


Use parenthesis in your regular expression and the result will be broken out into an array. For example:

x='Unnecessary:12357927251data'
x.scan(/(:\d+)(.+)$/)
=> [[":12357927251", "data"]]
x.scan(/:\d+(.+$)/).flatten
=> ["data"]
like image 26
bta Avatar answered Oct 20 '22 18:10

bta