" ...">

Extract substring from string in Ruby using regex

How to extract a substring from a string in Ruby?

Example:

String1 = "<name> <substring>" 

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

+79
string substring ruby regex
Nov 06 2018-10-11T00:
source share
5 answers
 String1.scan( /<([^>]*)>/).last.first 

scan creates an array that for each <item> in String1 contains the text between < and > in a singleton array (because when used with groups containing regular expressions, scan creates an array containing captures for each match). last gives you the last of these arrays and first , then returns a string in it.

+86
Nov 06 '10 at
source share
 "<name> <substring>"[/.*<([^>]*)/,1] => "substring" 

No need to use scan if we need only one result.
No need to use match if we have String[regexp,#] .

See: http://ruby-doc.org/core/String.html#method-i-5B-5D

Note: str[regexp, capture] β†’ new_str or nil

+222
Nov 06 '10 at 21:00
source share

You can use regex for this quite easily ...

Resolution of spaces around a word (but not their preservation):

 str.match(/< ?([^>]+) ?>\Z/)[1] 

Or without valid spaces:

 str.match(/<([^>]+)>\Z/)[1] 
+12
Nov 06 '10 at 20:59
source share

Here is a slightly more flexible approach using the match method. In this case, you can extract more than one line:

 s = "<ants> <pants>" matchdata = s.match(/<([^>]*)> <([^>]*)>/) # Use 'captures' to get an array of the captures matchdata.captures # ["ants","pants"] # Or use raw indices matchdata[0] # whole regex match: "<ants> <pants>" matchdata[1] # first capture: "ants" matchdata[2] # second capture: "pants" 
+8
Aug 30 '13 at 19:04 on
source share

The simplest scan would be:

 String1.scan(/<(\S+)>/).last 
+1
Jun 08 '16 at 15:47
source share



All Articles