Extract a substring from a string in Ruby using a regular expression

Madhusudhan picture Madhusudhan · Nov 6, 2010 · Viewed 147.3k times · Source

How can I extract a substring from within a string in Ruby?

Example:

String1 = "<name> <substring>"

I want to extract substring from String1 (i.e. everything within the last occurrence of < and >).

Answer

Nakilon picture Nakilon · Nov 6, 2010
"<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