tags:

views:

185

answers:

3

I understand how to check for a pattern in string with regexp in ruby. What I am confused about is how to save the pattern found in string as a separate string.

I thought I could say something like:

if string =~ /regexp/ 
  pattern = string.grep(/regexp/)

and then I could be on with my life. However, this isn't working as expected and is returning the entire original string. Any advice?

+4  A: 

You're looking for string.match() in ruby.

irb(main):003:0> a
=> "hi"
irb(main):004:0> a=~/(hi)/
=> 0
irb(main):005:0> a.match(/hi/)
=> #<MatchData:0x5b6e8>
irb(main):006:0> a.match(/hi/)[0]
=> "hi"
irb(main):007:0> a.match(/h(i)/)[1]
=> "i"
irb(main):008:0>

But also for working with what you just matched in the if condition you can use $& $1..$9 and $~ as such:

irb(main):009:0> if a =~ /h(i)/
irb(main):010:1> puts("%s %s %s %s"%[$&,$1,$~[0],$~[1]])
irb(main):011:1> end
hi i hi i
=> nil
irb(main):012:0>
dlamblin
Works, appreciate it
Atreides
+3  A: 

You can also use the special variables $& and $1-$n, like so:

if "regex" =~ /reg(ex)/
  puts $&
  puts $1
end

Outputs:

regex
ex

$~ also contains the MatchData object. See also: http://www.regular-expressions.info/ruby.html.

Taylor Hughes
+1  A: 

I prefer some shortcuts like:

email = "Khaled Al Habache <[email protected]>"
email[/<(.*?)>/, 1] # => "[email protected]"
khelll