Extract a substring from a string in Ruby using a regular expression
String1.scan(/<([^>]*)>/).last.first
scan
creates an array which, for each <item>
in String1
contains the text between the <
and the >
in a one-element array (because when used with a regex containing capturing groups, scan creates an array containing the captures for each match). last
gives you the last of those arrays and first
then gives you the string in it.
"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"
No need to use scan
, if we need only one result.
No need to use Python's match
, when we have Ruby's String[regexp,#]
.
See: http://ruby-doc.org/core/String.html#method-i-5B-5D
Note: str[regexp, capture] → new_str or nil