Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regular expressions

Tags:

regex

ruby

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?

like image 532
Atreides Avatar asked Feb 06 '26 00:02

Atreides


1 Answers

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> 
like image 129
dlamblin Avatar answered Feb 08 '26 04:02

dlamblin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!