user1916608
user1916608

Reputation: 51

Extract string in regex

im kinda new to Ruby but i have a question to regex in Ruby.

I have a String and i want to save the number in the string in a new variable and just the number. ruby is a pink to blood-red colored gemstone, a variety8of the mineral corundum (aluminium oxide). My Text ist

ruby is a pink to blood-red colored gemstone, a variety8of the mineral corundum (aluminium oxide). 

My regular expression is:

/blood-red colored gemstone, a variety(.*?)of the mineral corundum/m

Now i want to save the result in a new variable. So lets say:

var1 = 'ruby is a pink to blood-red colored gemstone, a variety8of the mineral corundum (aluminium oxide).'

and

var2 = var1[/blood-red colored gemstone, a variety(.*?)of the mineral corundum/m]

Now the result is the whole sentence from blood-red ... to ... mineral corundum. but how can i get access to the middle without the borders. In Rubular it is shown as a "group" ( in my case i want access to the digit inside a sentence). How can i get access to this group?

You can watch my example here in Rubular http://rubular.com/r/PgAgwRw3a5

Thank you very much

Upvotes: 2

Views: 81

Answers (2)

Simone Carletti
Simone Carletti

Reputation: 176562

In Ruby each group is stored in a match. If you explicitly use String#match, a MatchData is returned and you can access the matches.

s = "ruby is a pink to blood-red colored gemstone, a variety8of the mineral corundum (aluminium oxide)."
r = /blood-red colored gemstone, a variety(.*?)of the mineral corundum/m

m = s.match(r)
m[1]
 => "8" 

or

s.match(r)[1]
 => "8" 

There are several shortcuts, more or less readable. For instance you can use String#slice.

s.slice(r, 1)
 => "8" 

or the global variables

if s =~ m
  # $1 is the first match
  $1
end

If you are 100% sure the input is matched, then slice is a good option. If you need to perform some kind of test, then you may want to check that a match occurs.

Upvotes: 1

Uri Agassi
Uri Agassi

Reputation: 37419

From the documentation:

If a Regexp is supplied, the matching portion of the string is returned. If a capture follows the regular expression, which may be a capture group index or name, follows the regular expression that component of the MatchData is returned instead.

So, this should work:

 var2 = var1[/blood-red colored gemstone, a variety(.*?)of the mineral corundum/m, 1]
 # => "8"

Upvotes: 2

Related Questions