Extract a Substring from a String in Ruby Using a Regular Expression

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.

Ruby - extracting a substring from a string

You can use gsub:

arr = ["/currencies/avoncoin/"]
arr = arr.map{ |s| s.gsub("/currencies/", "").gsub("/","") }

best way to find substring in ruby using regular expression

If string = "http://stackoverflow.com",

a really easy way is string.split("http://")[1]. But this isn't regex.

A regex solution would be as follows:

string.scan(/^http:\/\/(.+)$/).flatten.first

To explain:

  1. String#scan returns the first match of the regex.
  2. The regex:

    • ^ matches beginning of line
    • http: matches those characters
    • \/\/ matches //
    • (.+) sets a "match group" containing any number of any characters. This is the value returned by the scan.
    • $ matches end of line
  3. .flatten.first extracts the results from String#scan, which in this case returns a nested array.

Get substring from string using regex in ruby

Running the regex in multiline mode should solve the issue:

(?m)Unhandled Exception:(.*?):

Code:

re = /Unhandled Exception:(.*?):/m
str = 'g4net:HostName=abc}
Unhandled Exception:
System.NullReferenceException: Object reference not set to an
'

# Print the match result
str.scan(re) do |match|
puts match.to_s
end

Extract a substring in Ruby using a regular expression

Here's a regex that will retrieve the field name and the value separately:

text = "A-field:name.23.134 => 6"
matches = text.match(/([^:]+:[^=\.\s]+)(\.\d+)*\s*=>\s*(.+)/)
puts "Field: #{matches[1]}"
puts "Value: #{matches[3]}"
puts "#{matches[1]} => #{matches[3]}"

The output of this is:

Field: A-field:name
Value: 6
A-field:name => 6

Extract substring from string using key pattern and delimiter using Ruby

You can use this regular expression:

mynames=([^\s]+)

And then, look for the first group: $1


Here is a live example in JavaScript (works also in other languages):