Ruby regular expressions

I understand how to check a pattern in a string with regexp in ruby. I am confused since saving the pattern found in the string as a separate string.

I thought I could say something like:

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

and then I could continue my life. However, this does not work as expected and returns the entire source string. Any tips?

+3
source share
3 answers

You are looking string.match()at 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 agreed on in the if condition, you can use $& $1.. $9and $~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> 
+6
source

You can also use the special variables $ & and $ 1- $ n, for example:

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

Outputs:

regex
ex

$~ MatchData. . : http://www.regular-expressions.info/ruby.html.

+3

I prefer a few shortcuts like:

email = "Khaled Al Habache <khellls@gmail.com>"
email[/<(.*?)>/, 1] # => "khellls@gmail.com"
+1
source

Source: https://habr.com/ru/post/1717492/


All Articles