Match strings with regular expressions
In Ruby you can use String#=~
to compare a string with regexp, returning the first index where it is found. For example let's search for the first ?
in this string:
"www.example.com/search?meatloaf" =~ /\?/
=> 22
If there is no match, it returns nil
"www.example.com" =~ /\?/
=> nil
BONUS:
When using Regexp#=~
, which functions very similarly, you can use a regexp with named captures to store them in local variables.
/(?<search_params>\?.+)/ =~ "www.example.com/search?lasagna"
=> 22
search_params
=> "?lasagna"
Tweet